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

helderburato profile image Helder Burato Berto 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"];

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


markdown guide

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


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.


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


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