【问题标题】:javascript: construct a function that compares input arrays and returns a new array with elements found in all of the inputs [duplicate]javascript:构造一个函数,比较输入数组并返回一个新数组,其中包含在所有输入中找到的元素[重复]
【发布时间】:2019-06-09 01:14:50
【问题描述】:

我正在尝试构建一个函数交集,它比较输入数组并返回一个新数组,其中包含在所有输入中找到的元素。

下面是我的代码:

function intersection (arr){

  let newArray = []; 

  let concatArray = arr.reduce((a,e) => a.concat(e), [])
  //let uniqueArray = Array.from(new Set(concatArray));

  // console.log(concatArray)

  for (let i=0; i<concatArray.length; i++){
    let element = concatArray[i]; 

    concatArray.shift()

    if (concatArray.includes(element)){
      newArray.push(element); 
    }

  }
  return newArray; 
}

const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3])); // should log: [5, 15]

我的代码返回:[ 5, 15, 15, 1, 7, 10, 5 ]which is away

我做错了什么?

【问题讨论】:

    标签: javascript arrays function loops intersection


    【解决方案1】:

    您可以简单地使用.filter().every() 方法来获得所需的输出:

    const arr1 = [5, 10, 15, 20];
    const arr2 = [15, 88, 1, 5, 7];
    const arr3 = [1, 10, 15, 5, 20];
    
    const intersection = ([first, ...rest]) => first.filter(
        v => rest.every(arr => arr.includes(v))
    );
    
    console.log(intersection([arr1, arr2, arr3]));

    【讨论】:

      猜你喜欢
      • 2021-10-02
      • 2019-10-29
      • 2016-04-22
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 2019-10-18
      相关资源
      最近更新 更多