🔥 Quick Tip: Update an array and avoid mutation
Helder Burato Berto

Helder Burato Berto @helderberto

About: Software Engineer who loves to craft challenging projects and share knowledge with people.

Location:
Portugal
Joined:
Oct 15, 2017

🔥 Quick Tip: Update an array and avoid mutation

Publish Date: May 18 '20
20 4

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.

Comments 4 total

  • Samuel Huang
    Samuel Huang May 19, 2020

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

  • Karran Besen
    Karran BesenMay 20, 2020

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

    • Helder Burato Berto
      Helder Burato BertoMay 20, 2020

      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.

Add comment