Home > Back-end >  Set Value of multidimensional Arssx item
Set Value of multidimensional Arssx item

Time:01-30

Hallo is this in js / typescript to implement? I have this function:

setValueOfArray(a:Array<any>, p:Array<number>, value:any);

Example:

setValueArray(a, [0,4,7], 33) {

// This should come out
a[0][4][7] = 33;
return a;

}

However, the length of p is undetermined.

Couldn't find a solution, does anyone have one? Thx.

CodePudding user response:

You don't need to use eval() here (and that is best avoided whenever possible). Instead, you can take the last index from your indexes array using .pop() to get 7, leaving you with an indexes array of [0, 4]. You can then loop through this array and for each index you loop over, grab the array from a at that index and store that array in a variable. That variable (which is acc below), can then be accessed in the next iteration when you loop over the next index. Below this loop is done using .reduce(). Once you have the final array, you can use the final index you popped off of your indexes array to update your target array with the new value.

See example below:

const a = [[[], [], [], [], [0, 1, 2, 3, 4, 5, 6, 7]]];

function setValueArray(arr, indexes, num) {
  const lastIdx = indexes.pop();
  const finalArr = indexes.reduce((acc, idx) => acc[idx], arr);
  finalArr[lastIdx] = num;
}

setValueArray(a, [0,4,7], 33);
console.log(a); // [[[],[],[],[],[0,1,2,3,4,5,6,33]]]

The above can be written using a regular for..of loop if that is easier to understand:

const a = [[[], [], [], [], [0, 1, 2, 3, 4, 5, 6, 7]]];

function setValueArray(arr, indexes, num) {
  const lastIdx = indexes.pop();
  let finalArr = arr;
  for(const idx of indexes)
    finalArr = finalArr[idx];
  finalArr[lastIdx] = num;
}

setValueArray(a, [0,4,7], 33);
console.log(a); // [[[],[],[],[],[0,1,2,3,4,5,6,33]]]

CodePudding user response:

Can you give some more info about the application?

I made a function that does what you wanted. Here is the code:

const setValueOfArray = (a, p, value) => {
  let s = "";
  for (const num of p) {
    s  = `[${num}]`;
  }
  eval(`a${s} = ${typeof value === "string" ? `\"${value}\"` : value}`);
  return a;
};
  •  Tags:  
  • Related