DEV Community 👩‍💻👨‍💻

Helder B. Berto
Helder B. Berto

Posted on • Updated 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 B. 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
 
helderberto profile image
Helder B. Berto Author

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

🌚 Life is too short to browse without dark mode