Home > front end >  what is the difference between splice and filter for the use in delete?
what is the difference between splice and filter for the use in delete?

Time:05-04

members is a prop that come to the child component from parent component when i use splice on copymembers a copy of members it is getting updated in parent component

copyMembers = [...members]
copyMembers[memberIndex].notes.splice(noteIndex,1);

but instead of doing it like above if i use filter then it is not getting updated in parent component why is this happening what is the difference between them

copyMembers = [...members]
copyMembers[memberIndex].notes = copyMembers[memberIndex].notes.filter((item : any) => item.notesId !== notesId)

CodePudding user response:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place [1]

This explains the behavior you'e seeing with splice. You're passing the data down into the child and the child us updating actual array reference, thus the parent component is being updated.

The filter() method creates a new array with all elements that pass the test implemented by the provided function [2]

When you use filter, this doesn't happen because you're creating a new array with all of the elements that pass the criteria.

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

CodePudding user response:

When you copy an array in JS it only does a shallow copy. This means that nested properties share the same reference, in your case notes is shared by reference so if you modify it in the copy it gets modified in the source.

splice() (mutable) modifies the array, and hence also the copied array since they share same reference. filter() (immutable) creates a new array and does not modify the original one.

CodePudding user response:

The filter() method creates a new array with all elements that pass the test implemented by the provided function. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements and returns the removed item(s). splice() changes original array

  • Related