Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use a reduce function to find the intersection/union between a set of arrays in javascript functional programming?

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]
like image 931
Jull Weber Avatar asked Dec 11 '22 13:12

Jull Weber


1 Answers

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))) };
like image 157
ajaix Avatar answered May 18 '23 14:05

ajaix