How to update a value in 2D array in redux reducer?

Viewed 1569

I am trying to update a value at index (i, j) in a 2D array using spread operator in redux reducer. My reducer looks like:

export default (state, action) => {
switch(action.type) {
 case INSERT:
   return {
    ...state,
    myArray: [
     ...state.myArray.slice(0, action.i),
     ...state.myArray[action.i] : [
         ...state.myArray[action.i].slice(0, action.j),
         action.newValue,
         ...state.myArray[action.i].slice(action.j),
     ]
     ...state.myArray.slice(action.i),
    ]
  },
};

My array looks like:

let my Array = [ [1,2,5],[5,8,9],[2,6,9]]

How do i update a new value at index (i, j) using redux Immutable Update Patterns?

3 Answers

Or without map at all, and just with spread operator and dynamic key:

let arr = [
  [1, 2, 5],
  [5, 8, 9],
  [2, 6, 9]
];

const newValue = 6;
const i = 1;
const j = 2;

let myArr = Object.assign([...arr], {
  [i]: Object.assign([...arr[i]], {
    [j]: newValue
  })
})

console.log(myArr);

You can use two nested .map calls to update the values at path i and j

return {
    ...state,
    myArray: state.myArray.map((innerArray, index) => {
        if (index === action.i) return innerArray.map((item, index) => {
            if (index === action.j) return action.newValue
            return item
        })
        return innerArray
    })
}

This is much simpler than using the spread operator, since the value you need to change is at a dynamic index. Plus, it is immutable, which is the redux way

let arr = [[1,2,5],[5,8,9],[2,6,9]];

const payload = 6;
const i = 1;
const j = 2;

const result = arr.map((inner, index) => (i === index) ? inner.reduce(
    (arr, item, index) => j === index ? [...arr, payload, item] : [...arr, item], []) : inner);

console.log(result);

Related