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?
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.
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.
The splice() method allows you to insert new elements into an array while deleting existing elements simultaneously.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With