0

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

Kondal
  • 2,384
  • 4
  • 21
  • 39
  • Use array filter – Hassan Imam Dec 09 '17 at 09:36
  • please add the wanted result - and what you have tried. – Nina Scholz Dec 09 '17 at 09:37
  • Please read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Dec 09 '17 at 09:39
  • 3
    Possible duplicate of [Javascript arrays: remove all elements contained in another array](https://stackoverflow.com/questions/19957348/javascript-arrays-remove-all-elements-contained-in-another-array) – Madhavan.V Dec 09 '17 at 09:44

5 Answers5

2

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);
Ori Drori
  • 145,770
  • 24
  • 170
  • 162
2

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);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
2

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)
Mamun
  • 58,653
  • 9
  • 33
  • 46
1

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);
Sajeetharan
  • 186,121
  • 54
  • 283
  • 331
1

 var a = [1,2,2,2,5];
 var b = [2];
var result= a.filter(function(x) { 
  return b.indexOf(x) < 0;
});
console.log(result)
vicky patel
  • 575
  • 2
  • 6
  • 13