Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Set Value of multidimensional Arssx item

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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]]]

about 4 years ago · Juan Pablo Isaza Report

0

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;
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!