Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get arrays intersection include duplicate values using Javascript

I need something like lodash.intersectionWith but I also need duplicated values in result array.

Example:

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.intersectionWith(objects, others, _.isEqual);

Expected Result:

[{ 'x': 1, 'y': 2 },{ 'x': 1, 'y': 2 }]

Thanks in advance!

like image 802
Mikhail Avatar asked Sep 02 '25 02:09

Mikhail


1 Answers

You can find the intersection by filtering out items from the first array that don't match items in the second. Any duplicates in the first array will be kept.

var intersectwith = function(f,xs,ys){
    return xs.filter(function(x){
        return ys.some(function(y){
            return f(x,y);
        });
    });
};

var equals = function(x,y){
    return x === y;
};
console.log(intersectwith(equals, [1,2,3], [1,1,2,2,4]));
console.log(intersectwith(equals, [1,1,2,2,4], [1,2,3]));

Or, more readably, using ES6:

const intersectwith = (f,xs,ys) => xs.filter(x => ys.some(y => f(x,y)));
const equals = (x,y) => x === y;

console.log(intersectwith(equals, [1,2,3], [1,1,2,2,4]));
console.log(intersectwith(equals, [1,1,2,2,4], [1,2,3]));

Substitute _.isEqual for equals for comparing objects: jsfiddle.

Useful documentation:
Array.prototype.filter
Array.prototype.some

like image 99
1983 Avatar answered Sep 07 '25 08:09

1983