Saturday, June 22, 2024
HomeJavaScriptCopy an array and change one component at a selected index with...

Copy an array and change one component at a selected index with fashionable JavaScript


How do you change an array component at a given index?

Is that this a trick query? Probably not.

const numbers = [1, 2, 3, 4, 5];
numbers[1] = 'new worth';
console.log(numbers); 

However once you’re utilizing React or any framework betting on immutability, simply altering an array entry will result in delicate bugs as a result of the array will nonetheless be the identical object with the identical reference. In an immutable world, knowledge updates at all times need to lead to a brand new object reference.

How will you change an array component through its index and spit out a brand new array in the identical go then? A 12-years-old Stack Overflow query with 1.5m views has tons of recommendation, however as a result of it is so previous and has a whole bunch of upvotes, it is not exhibiting essentially the most fashionable answer within the high space.

Let’s have a fast have a look at inventive solutions.

The previous approach to copy an array and alter one merchandise

You actually may iterate over the array and construct up a brand new one with previous forEach loop.

operate changeItem(array, index, newValue) {
  const newArray = [];
  array.forEach((num, i) => {
    if (i === index ) return newNumbers.push(newValue); 

    newArray.push(num);
  })
  return newArray;
}

const numbers = [1, 2, 3, 4, 5];
const updatedNumbers = changeItem(numbers, 1, 'new worth');
console.log(updatedNumbers);             
console.log(numbers === updatedNumbers); 

However this is not nice. Doing it with map is already a bit nicer…

operate changeItem(array, index, newValue) {
  return array.map((worth, i) => {
    if (i === index) return newValue;

    return worth;
  })
}

const numbers = [1, 2, 3, 4, 5];
const updatedNumbers = changeItem(numbers, 1, 'new worth');
console.log(updatedNumbers);              
console.log(numbers === updatedNumbers);  

And for the creatives, should you belong to this small group of oldsters who keep in mind the distinction between slice and splice, you can additionally use considered one of these.

operate changeItem(array, index, newValue) {
  return [
    ...array.slice(0, index),
    newValue,
    ...array.slice(index + 1)
  ];
}

const numbers = [1, 2, 3, 4, 5];
const updatedNumbers = changeItem(numbers, 1, 'new worth');
console.log(updatedNumbers);             
console.log(numbers === updatedNumbers); 

Okay, this one (☝️) is definitely horrible.

However what if I instructed you that copying an array and altering one entry is cross-browser supported in JavaScript as we speak?

The brand new manner — copy an array and alter an entry with with()

All fashionable browsers assist with() nowadays.

And with it, this complete train turns into a nifty one-liner.

const numbers = [1, 2, 3, 4, 5];
const updatedNumbers = numbers.with(1, 'new worth');
console.log(updatedNumbers);             
console.log(numbers === updatedNumbers); 

Thanks fashionable JavaScript!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments