1

I have two different arrays and I want to remove all copies of first array's elements which exist in second one. I've tried some splice and indexOf methods but couldn't achieved it. Checked some of other posts but couldn't find what I'm exactly looking for. Here is an example code below. Thank you all.

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


function func(container, removing){
  let result = //i want to write a function there which will remove all duplicates of "removing" from "container".
  return result; // result = [1, 4, 5]
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Kaan G
  • 219
  • 4
  • 13

5 Answers5

9

Here you go

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


let difference = (a, b) => a.filter(x => !b.includes(x));

console.log(difference(container, removing))

If, for some reason, you're concerned about efficiency of this, you can replace the linear includes checks with O(1) Set lookups:

let difference = (a, b) => (s => a.filter(x => !s.has(x)))(new Set(b))
georg
  • 211,518
  • 52
  • 313
  • 390
1

Use filter with includes:

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


function func(container, removing){
  let result = container.filter(e => !removing.includes(e));
  return result;
}

console.log(func(container, removing));

ES5 syntax:

var container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
var removing = [2, 3];


function func(container, removing){
  var result = container.filter(function(e) {
    return removing.indexOf(e) == -1;
  });
  return result;
}

console.log(func(container, removing));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You can do it like this,

function func(container, removing){
  let result = container.filter(data => {
                   if(removing.indexOf(data) < 0) return true;})
  return result; // result = [1, 4, 5]
}
Pavan Skipo
  • 1,757
  • 12
  • 29
0

This will do:

function func(container, removing){
    let result = container.filter(x => !removing.includes(x));
    return result;
}
Mu-Tsun Tsai
  • 2,348
  • 1
  • 12
  • 25
0

Try this:

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


const func = (container, removing) => container.filter(res=>!removing.includes(res));
  
console.log(func(container,removing));
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23