Filter and delete filtered elements in an array

Another way is filtering in two list like this:

const originalList = [{condition:true}, {condition: false}, {condition: true}];

// wished lists
const listWithTrue = originalList.filter(x=>x.condition);
const listWithFalse = originalList.filter(x=>!x.condition); // inverse condition

The Array.prototype.filter() method is used to collect an element set not only one item. If you would like to get one item by evaluating a condition then you have three other options:

  • Array.prototype.indexOf()
  • Array.prototype.findIndex()
  • Array.prototype.find()

Accordingly only if you want to make an operation on more than one item you should think of using the filter function. None of the answers is complete in terms of the job that is needed to be done.

They use the filter function to isolate a set (happens to be only one item in this example) but they don't show how to get rid of the whole set. Well ok, let's clarify.

If you want to do find and delete only one item of your array it shall be done like this

var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}];
a.splice(a.findIndex(e => e.name === "tc_001"),1);
console.log(a);

However since you mention "specific elements" in plural, then you will need to collect a set of selected items and do the above job one by one on each element in the set. So the proper approach would be.

var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}],
    b = a.filter(e => e.name === "tc_001");
b.forEach(f => a.splice(a.findIndex(e => e.name === f.name),1));
console.log(a);

Regardless of how many elements there are in your selected list, this will do your job. Yet I believe although this looks logical it does tons of redundant job. First filters and then per filtered element does index search this and that. Although I know that findIndex is crazy fast still I would expect this one to turn out to be noticeably slow especially with big arrays. Let's find an O(n) solution. Here you go:

var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}];
a = a.reduce((p,c) => (c.name !== "tc_001" && p.push(c),p),[]);
console.log(a);

So this must be it.