javascript: construct a function that compares input arrays and returns a new array with elements found in all of the inputs

Viewed 242

I am trying to construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.

Below is my code:

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]

My code returns: [ 5, 15, 15, 1, 7, 10, 5 ]which is way off

What am I doing wrong?

1 Answers

You can simply use .filter() and .every() methods to get the desired output:

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]));

Related