remove common elements of two arrays in jquery
Asked Answered
C

4

8

I want to remove common elements of two arrays in jquery. I have two arrays:

A = [0,1,2,3]
B = [2,3]

and result should be [0, 1].

Please help

Charismatic answered 2/6, 2014 at 9:8 Comment(3)
Did you try something ? For example looping ?Misfeasance
pls help me with some inbuilt function.Charismatic
BTW filter returns common elements in two array ie. [2,3]Charismatic
C
14

You can filter array A by checking its elements position in array B:

C = A.filter(function(val) {
 return B.indexOf(val) == -1;
});

Demo

Cantankerous answered 2/6, 2014 at 9:12 Comment(2)
filter and indexOf are not supported in some browsers, notably IE.Armijo
Only very old versions of IE. It's fine for current ones.Misfeasance
J
7

ES6 version of Milind Anantwar's answer. May require Babel.

const A = [1, 2, 3, 4];
const B = [2, 4];
const C = A.filter(a => !B.includes(a));
console.log(C) // returns [1, 3]
Jazminejazz answered 24/3, 2017 at 14:19 Comment(0)
M
2

Use the Set type from ES6. Then the spread operator to build an array from the Set. A Set type can only hold unique items.

const A = [1, 2, 3, 4];
const B = [2, 4];
const C = [...new Set(A,B)];

console.log(C);



(4) [1, 2, 3, 4]
Maxama answered 14/3, 2019 at 23:30 Comment(0)
A
1

Checkout the library underscore.js.

Say you have two arrays,

var a = [0,1,2,3];
var b = [2, 3];

First find the union.

var all = _.union(a, b);

Then find the intersection.

var common = _.intersection(a, b);

The final answer should be the difference between the union, and the intersection.

var answer = _.difference(all, common)
Armijo answered 2/6, 2014 at 9:10 Comment(1)
Including an entire library just to de-dupe a couple of arrays is massive overkill.Penetralia

© 2022 - 2024 — McMap. All rights reserved.