代码之家  ›  专栏  ›  技术社区  ›  jgrewal

Javascript;将公共元素从2个列表推送到新列表

  •  0
  • jgrewal  · 技术社区  · 4 年前
    let listOne = [Bill, Joe, Trever, Neil, Jim, Pam, Michael]
    let listTwo = [Petter, Pam, Steven, Jim, Michael, Scott]
    

    我有两个列表,但我想创建一个新列表,其中只包含两个列表中的名称。

    [Jim, Pam, Michael]
    

    我需要帮助的是:

    我觉得有更好的办法。不必嵌套我的循环。也许是以某种方式同时过滤两个列表

    4 回复  |  直到 4 年前
        1
  •  3
  •   2pichar    4 年前

    您可以使用Array.prototype.reduce,让回调函数搜索其他列表,并且仅在名称位于其他列表中时插入该名称。

    listOne.reduce((prev, cur)=>{
        if(listTwo.includes(cur)){
            prev.push(cur);
        }
        return prev;
    });
    
        2
  •  2
  •   Vítor França    4 年前

    您可以这样做:

    let listOne = [Bill, Joe, Trever, Neil, Jim, Pam, Michael]
    let listTwo = [Petter, Pam, Steven, Jim, Michael, Scott]
    
    let result = listOne.filter(item => listTwo.includes(item))
    
        3
  •  2
  •   DecPK    4 年前

    Set filter 在这里检查是否存在 name 在里面 设置 如果你想使用 has 方法 set .

    let listOne = ["Bill", "Joe", "Trever", "Neil", "Jim", "Pam", "Michael"];
    let listTwo = ["Petter", "Pam", "Steven", "Jim", "Michael", "Scott"];
    
    const set = new Set(listOne);
    const result = listTwo.filter(name => set.has(name));
    // or
    // const result = listTwo.filter(set.has.bind(set));
    console.log(result);
        4
  •  0
  •   WindrunnerMax    4 年前

    const listOne = ["Bill", "Joe", "Trever", "Neil", "Jim", "Pam", "Michael"]
    const listTwo = ["Petter", "Pam", "Steven", "Jim", "Michael", "Scott"]
    
    const newList = listOne.filter(item => listTwo.indexOf(item) > -1)
    console.log(newList)
    推荐文章