I\'m stuck with this problem for 3 days now... Someone please help me.
Challenge 5
Construct a functionintersection
You could reduce the array by filtering with just checking if the other array contains the value.
This works for arrays with unique values.
Array#reduce:
If no
initialValue
is provided, thenaccumulator
will be equal to the first value in the array, andcurrentValue
will be equal to the second.The callback
a.filter(v => b.includes(v))
filters array
a
. If the arrayb
includes the value ofa
, then this valuev
is included in theaccumulator
for the next iteration or as final result.accumulator currentValue new accumulator a b result -------------------- -------------------- -------------------- [ 5, 10, 15, 20] [15, 88, 1, 5, 7] [ 5, 15] [ 5, 15] [ 1, 10, 15, 5, 20] [ 5, 15]
function intersection(arrayOfArrays) {
return arrayOfArrays.reduce((a, b) => a.filter(v => b.includes(v)));
}
console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));