I wanted to create a small application that could check arrays for intersecting values and reduce those arrays in a new one with only intersecting numbers. I was able to accomplish this using built in prototype methods but wanted to do it with my own defined functions.
const forEach = (array, callback) => {
for(var i = 0; i < array.length; i++) {
callback(array[i])
}
}
const reduce = (array, callback, initValue) => {
accumulator = initValue
const reduceFunction = (el) => {accumulator += callback(el)}
forEach(array, reduceFunction)
return accumulator
}
const intersectionWithReduce = (...arrays) => {
currentValue = []
reduce(arrays, el => currentValue += arrays.filter(currentValue.includes(el)), currentValue)
return currentValue
}
console.log(intersectionWithReduce([1, 2, 3, 20], [15, 88, 1, 2, 7], [1, 10, 3, 2, 5, 20]));
// expected output of [1,2]
// actual output TypeError: false is not a function
Since false
is being returned from currentValue I am throughly confused and will admit that recently the more I look at this the more I feel my solutions aren't making sense. What am I missing to make my reduce function work in this context.