Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array intersection (set-theoretic) with Array.prototype.reduce

I have two arrays [a,b,c,d] and [b,d,f,h].

I want to get an array back with the common elements [b,d].

I can achieve that with a combination of filter and indexOf:

[a,b,c,d].filter(el => [b,d,f,h].indexOf(el) !== -1)

but I was wondering if and how I can do the same with reduce.

I admit that, despite looking at many examples, reduce still is to me one of the most obscure JS methods, so I'd really appreciate some advice.

like image 898
U r s u s Avatar asked Jan 05 '23 23:01

U r s u s


1 Answers

ES6, a propoosal with Array#includes

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

On every loop of aa, reduce adds the element to the result array if the value is found in the test array bb. If not found, the former result is returned.

var aa = ['a','b','c','d'],
    bb = ['b','d','f','h'],
    cc = aa.reduce((r, a) => bb.includes(a) && r.concat(a) || r, []);

console.log(cc);

Just a smarter approach with using a single array which contains all arrays.

var aa = ['a','b','c','d'],
    bb = ['b','d','f','h'],
    result = [aa, bb].reduce((a, b) => a.filter(c => b.includes(c)));

console.log(result);
like image 94
Nina Scholz Avatar answered Jan 08 '23 14:01

Nina Scholz