Intersection of an array (set-theoretic) with Array.prototype.reduce

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

I want to return an array with common elements [b,d].

I can achieve this with a combination of filterand indexOf:

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

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

I admit that, despite many examples, reduceit is still one of the most obscure JS methods, so I would really appreciate some advice.

+4
source share
3 answers

ES6, prooosal with Array#includes

includes() , , true false .

aa, , bb. , .

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);
Hide result

, .

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);
Hide result
+3

. .

. : https://jsfiddle.net/c69vgzL4/

var a = ['a','b','c','d']
var b = ['b','d','f','h']

var number_of_common = b.reduce(function(prev, next) {
    return prev + (a.indexOf(next) + 1 ? 1 : 0)
}, 0)

$('body').html(number_of_common)
+2

, n ... Array.prototype.intersect()

Array.prototype.intersect = function(...a) {
  return [this,...a].reduce((p,c) => p.filter(e => c.includes(e)));
}

var arrs = [[0,2,4,6,8],[4,5,6,7],[4,6]],
     arr = [0,1,2,3,4,5,6,7,8,9];

console.log(JSON.stringify(arr.intersect(...arrs)));

// or just do

console.log(JSON.stringify(["a","b","c","d"].intersect(["b","d","f","h"])));
Hide result
+1

All Articles