Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.
My solution works but it is very cumbersome:
const intersection = (arrMerged) => {
let finalArr = [];
let flatArray = [].concat(...arrMerged)
let newArr = [];
//console.log(flatArray)
//let interArray = [];
if (arrMerged[2] !== undefined){
newArr = arrMerged[0].map((elem) => {
if (arrMerged[1].includes(elem) && arrMerged[2].includes(elem)){
return elem;
}
})
}
else {
newArr = arrMerged[0].map((elem) => {
if (arrMerged[1].includes(elem)){
return elem;
}
})
}
newArr.forEach((elem) => {
if (elem !== undefined){
finalArr.push(elem)
}
})
return finalArr;
}
// Uncomment these to check your work!
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]
I would also like to use reduce() in my solution. Can someone provide an alternative code solution that uses reduce() and is more efficient please?
I would appreciate it if you can comment on what each line of your code is doing to help me understand.