Kondal
Kondal

Reputation: 2980

Subtracts values one list from another in javascript

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

Answers (5)

vicky patel
vicky patel

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

Mamun
Mamun

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

Nina Scholz
Nina Scholz

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

Sajeetharan
Sajeetharan

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

Ori Drori
Ori Drori

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

Related Questions