Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  150] [ 1]  / answers: 1 / hits: 154185  / 8 Years ago, mon, may 23, 2016, 12:00:00

I want to remove specific elements in the original array (which is var a). I filter() that array and splice() returned new array. but that doesn't affect 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);

More From » arrays

 Answers
16

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.


[#62063] Friday, May 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
julieth questions
;