3

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?

0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.