I have re-created foreach + map + reduce functions in js:
function forEach(array, callback) {
for (var i=0;i<array.length;i++) {
callback(array[i])
}
}
function mapWith(array, callback) {
var output= [];
forEach(array , function(el){
return output.push(callback(el))
});
return output;
}
function reduce(array, callback, initialValue) {
mapWith(array, function(el){
return initialValue = callback(initialValue, el);
})
return initialValue;
}
Now how would i use reduce to find the intersection between a set of arrays?
function intersection(arrays) {
}
// console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
// should log: [15, 5]
Also, how would I compare input arrays and return a new array that contains all elements. If there are duplicate elements, only added once to the new array. The order of the elements starting from the first element of the first input array is preserved.
function union() {
}
// console.log(union([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]));
// should log: [5, 10, 15, 88, 1, 7, 100]
I think Will Sentance will be OK with this too :)
const union = (arrays) => { return arrays.reduce((a, b) => Array.from(new Set(a.concat(b)))) };
const intersection = (arrays) => { return arrays.reduce((a, b) => a.filter(ele => b.includes(ele))) };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With