How to get the difference between two arrays?

I have 2 arrays:

arr1 = [[11,12],[11,13],[11,14], [12,13]];
arr2 = [[11,13],[11,14]];

Expected Result [[11,12],[12,13]].

How can I get the difference between two arrays? I am using lodash _.difference, but this gives me the wrong answer.

+4
source share
4 answers

Using only javascript and just for this and similar examples

var a1 = [[11,12],[11,13],[11,14], [12,13]];
var a2 = [[11,13],[14,11]];
var a3 = a1.filter(ar1 => !a2.some(ar2 => ar1.every(n1 => ar2.includes(n1))))
console.log(a3); // [[11,12],[12,13]]

Too many criteria to create a common solution.

, [11,12] [12,11], , , (ar1 === ar2) true. , , - ? , , , .

var a1 = [[11,12],[11,13],[11,14], [12,13]]
var a2 = [[11,13],[14,11],[12,14]];
a3 = [];
[[a1,a2],[a2,a1]].forEach(a=>{
    a3.push(...a[0].filter(
        ar1 => !a[1].some(
            ar2 => ar1.every(
                n1 => ar2.includes(n1)
            )
        )
    ))
});
console.log("[["+a3.join("], [")+"]]")
Hide result
0

_.differenceWith(), -. , , , -, .

result = _.differenceWith(arr1, arr2, _.isEqual);
+4

lodash. , , .

var arr1 = [[11,12],[11,13],[11,14], [12,13]];
var arr2 = [[11,13],[11,14],[12,14]];

var res = arr1.concat(arr2).map(x => x.join(",")).filter((x,i,arr) => arr.indexOf(x) === arr.lastIndexOf(x)).map(x => x.split(","));

console.log(res);
Hide result
0

() JS. , , .

var arr1 = [[11,12],[11,13],[11,14],[12,13]],
    arr2 = [[11,13],[11,14],[12,14]];
     res = arr1.reduceRight((p,c,i,a) => { var fi = p.findIndex(s => c.every(n => s.includes(n)));
                                           return fi !== -1 ? (a.splice(i,1),
                                                               p.splice(fi,1),
                                                               p)
                                                            :  p;
                                         },arr2)
               .concat(arr1);
console.log(res);
Hide result
0
source

Source: https://habr.com/ru/post/1665446/


All Articles