Reputation: 2980
How to remove all values from var a = [1,2,2,2,3]
which are present in var b=[2]
If a values is present in b variable all of its occurrences must be remove
var a = [1,2,2,2,5];
var b = [2];
const result = a.filter(function(el){
return /// which condition .?
});
How to remove the b var value. and we have many logics please answer it briefly
Upvotes: 0
Views: 112
Reputation: 705
var a = [1,2,2,2,5];
var b = [2];
var result= a.filter(function(x) {
return b.indexOf(x) < 0;
});
console.log(result)
Upvotes: 1
Reputation: 68923
Try the following by using array's filter()
:
var a = [1,2,2,2,5];
var b = [2];
var c = a.filter(item => !b.includes(item))
console.log(c)
Upvotes: 2
Reputation: 386680
You could take a Set
for the unwanted items.
var a = [1, 2, 2, 2, 5],
b = [2],
result = a.filter((s => v => !s.has(v))(new Set(b)));
console.log(result);
Upvotes: 2
Reputation: 222682
use array.filter
var first = [1, 2, 2, 2, 5];
var second = [2];
var result = first.filter(function(n) {
return second.indexOf(n) === -1;
});
console.log(result);
Upvotes: 1
Reputation: 192277
A simple solution is to use Array#filter, and check if the value exists using Array#indexOf:
var a = [1, 2, 2, 2, 5];
var b = [2];
var result = a.filter(function(n) {
return b.indexOf(n) === -1;
});
console.log(result);
However, this requires redundant iterations of the 2nd array. A better solution is to create a dictionary object from b
using Array#reduce, and use it in the filtering:
var a = [1, 2, 2, 2, 5];
var b = [2];
var bDict = b.reduce(function(d, n) {
d[n] = true;
return d;
}, Object.create(null));
var result = a.filter(function(n) {
return !bDict[n];
});
console.log(result);
Upvotes: 2