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

拈花ヽ惹草 提交于 2019-12-21 04:09:04

问题


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?


回答1:


Check this performance test out. It's has not that much to do with Angular, but more with JavaScript. If you're able just go for the fastest method available :)




回答2:


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




回答3:


In case you know the index using splice would be an O(1) operation while using filter is an O(n) operation.



来源:https://stackoverflow.com/questions/44435141/remove-object-in-array-using-filter-and-splice-which-one-is-best-approach-in-ang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!