Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

filter

splice

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?

like image 706
Harleen Kaur Arora Avatar asked Jun 08 '17 11:06

Harleen Kaur Arora


People also ask

What is difference between slice and splice in array methods?

The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.

How do you remove an object from an array filter?

pop - Removes from the End of an Array. shift - Removes from the beginning of an Array. splice - removes from a specific Array index. filter - allows you to programatically remove elements from an Array.

Which method is used to add or remove items JavaScript?

The splice() method allows you to insert new elements into an array while deleting existing elements simultaneously.

How do you remove an element from an array using splice?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.


2 Answers

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

like image 167
chrystian Avatar answered Oct 13 '22 03:10

chrystian


I think chrystian's answer is the right one but I want to add a warning (not related to performance but to avoid a potential undesired bug)

WARNING: One small detail, be careful when you use splice with indexOf. If indexOf returns (-1), that's to say the element wasn't found, splice will remove the last element of the array (negative indexing works).

If you decide to use splice instead of filter take that into consideration and check for the indexOf result before doing splice

like image 20
RCarranza Avatar answered Oct 13 '22 03:10

RCarranza