Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

63
Vistas
what is the difference between splice and filter for the use in delete?

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)
7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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

7 months ago · Juan Pablo Isaza Denunciar

0

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.

7 months ago · Juan Pablo Isaza Denunciar

0

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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.