Hi I delete an object in an array using two approaches:- splice and filter.
splice code here:-
(this.myArray).splice((this.myArray).indexOf(myobjec
In case you know the index using splice would be an O(1) operation while using filter is an O(n) operation.
Array.splice - will change the Array itself. (use: myArray.splice)
Array.filter - will return the filtered Array. (use: myFilteredArray = Array.filter)
This is a test result on an Array of 30 small objects. I ran it on jsbence.me:
There are several answers regarding performance, but there is another difference that wasn't explicitly mentioned between the two methods you are asking about:
The first method you wrote, using indexOf
, will only splice the first reference to myobject
in this.myArray
, as it says in the documentation,
The indexOf() method returns the first index at which a given element can be found
The second method you asked about using filter
, will remove every reference to myobject
in this.myArray
, in the case that you have multiple references to it in the array. Here is the line from filter's documentation that explains it:
Filter() calls a provided callback function once for each element in an array
And as chrystian said, filter also returns a new array, whereas splice modifies the array it was called on. For clarity, I've written a little gist that shows overloads of both options side-by-side. It has pretty clear documentation about the differences, so feel free to use it if it helps you at all. (If you prefer it as a prototype method, as some people do, here's that as well.) Since this question is specifically about Angular, the gists are in Typescript.
The second part of your question asked which was best. The best approach may be situationally based on two things:
myobject
referenced in this.myArray
?
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
I think that the main difference here is:
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