DEV Community

loading...

🔥 Quick Tip: Update an array and avoid mutation

helderburato profile image Helder Burato Berto Originally published at linkedin.com Updated on ・1 min read

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.

Discussion (4)

pic
Editor guide
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
helderburato profile image
Helder Burato Berto Author

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
helderburato profile image
Helder Burato Berto Author

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