Srinesh Srinesh - 6 months ago 13
Node.js Question

Filter and delete filtered elements in a array

I want to remove specific elements in original array (which is

var a
). I
filter()
that array and
splice()
returned new array. but that doesn't effect to the original array in this code. How can i easily remove those elements from the original array?

var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}]

var b = a.filter(function (e) {
return e.name === 'tc_001';
});

b.splice(0,1);

console.log(a);
console.log(b);

Answer

So if I understood, you want to remove the elements that matches the filter from the original array (a) but keep them in the new array (b) See if this solution is what you need:

var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}]

var b = a.filter(function (e) {
      return e.name === 'tc_002'
});

b.forEach(function(element) {
   console.log(element)
   var index = a.indexOf(element)
   console.log(index)
   a.splice(index, 1)
})

Result: a = [{"name":"tc_001"},{"name":"tc_003"}] b = [{"name":"tc_002"}]

Comments