Revels Revels - 4 months ago 7
Javascript Question

How to change one element in array by index in a functional style?

For example, I want to write something like:

const initial = [1, 2, 3, 4];
const indexIWantToChange = 2;

const obj = {
prop: () => {
const newArr = [...initial];
newArr[indexIWantToChange] = 'Something new';
return newArr;
}()
};


How to change one specific element in array by index without mutating the original array in a functional style?
Is there a one-liner of this maybe?

Answer

Object.assign might be useful:

Object.assign([], initial, { [indexIWantToChange]: 'Something new' })

Snippet:

const initial = [1, 2, 3, 4];
const indexIWantToChange = 2;

let prop = Object.assign([], initial, { [indexIWantToChange]: 'Something new' });

console.log(prop);

Comments