Mohitsinh Chavda
Mohitsinh Chavda

Reputation: 115

Manipulating index of array dynamically in javascript, just like we do this for object

This question is basically asked for redux state manipulation ease if one has to return array instead of object in redux array For manipulating dynamic property of object, we do like this

const myObj = {
   name : 'any name',
   email : 'any email',
   dob : 'any dob'
}

If I want to return new object after manipulating it and I want to manipulate properties dynamically from a single function I can do it with ease

return {
  ...myObj,
  [action.dynamicProp] : action.anyValue
}

But if I want to do the same with array, I can' t able to do that with spread syntax

const myArr = ['value1','value2','value3'];
return [...myArr,?????????]

So is it possible to do this using spread syntax? (One can do this without spread operator but the point is to do it with spread syntax)

Upvotes: 1

Views: 90

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370809

You can do it with spread, but you also have to .slice the portions of the array before and after the item you want to replace and spread them into the new array. For example, to replace the item at index 1:

const myArr = ['value1','value2','value3'];
const index = 1;
const output = [
   ...myArr.slice(0, index),
   'newItem',
   ...myArr.slice(index + 1),
];
 console.log(output);

You can also make a shallow copy of the array and assign to an index, but that's less functional:

const myArr = ['value1','value2','value3'];
const index = 1;
const output = [...myArr];
output[index] = 'newItem';
 console.log(output);

Upvotes: 3

Related Questions