Remove object in array using filter and splice which one is best approach in JavaScript?

Harleen Kaur Arora picture Harleen Kaur Arora · Jun 8, 2017 · Viewed 14.6k times · Source

Hi I delete an object in an array using two approaches:- splice and filter.

splice code here:-

(this.myArray).splice((this.myArray).indexOf(myobject), 1);

filter code here:-

(this.myArray).filter(obj => obj !== myobject);

Please tell us differences between both and which one is the best approach?

Answer

chrystian picture chrystian · Jun 8, 2017

I think that the main difference here is:

  • splice - lets you remove an element from this particular array
  • filter - won't touch the input array and will create and return new filttered array

angular has nothing to do here and when it comes to speed, splice will win

and small test as proof https://jsperf.com/array-splice-vs-array-filter/1