DEV Community

Helder Burato Berto
Helder Burato Berto

Posted on • Edited on • Originally published at linkedin.com

πŸ”₯ Quick Tip: Update an array and avoid mutation

On this simple trick I'll show how to remove an element from the array and add another one at the same index.

const people = ['John', 'Robert', 'Sylvia'];
const robertIndex = 1;

const slicedPeople = [...people.slice(0, robertIndex), 'Joe', ...people.slice(robertIndex+1, people.length)];

console.log(slicedPeople); // => output: ["John", "Joe", "Sylvia"];
Enter fullscreen mode Exit fullscreen mode

What did you think of this tip? Feel free to comment.

Top comments (4)

Collapse
 
karranb profile image
Karran Besen

Awesome, I think it won't be too hard to make a helper function that looks like ramda`s update with this snippet

Collapse
 
helderberto profile image
Helder Burato Berto

Thanks for the comment!
A thing I like to do is reproduce the methods for these packages like lodash,ramda to better understand what is doing on the deep side.

Collapse
 
upieez profile image
Samuel Huang

so this doesn't mutate the people array but creates a new one, slicedpeople, with elements from people right?

Collapse
 
helderberto profile image
Helder Burato Berto

Yep! Avoiding the mutation in the "people" array :)