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:
- How many times is
myobject
referenced in this.myArray
?
- If it occurs many times, and you want to remove all references, use filter
- If it occurs many times, and you only want to remove the first reference, use indexOf
- If it occurs only once, ask yourself question 2:
- Is performance a big concern?
- If it is, then do a benchmark for it using the engine that will be running the script, and use the most performant method
- If it isn't, use the one you find easiest to read.