2

I have an n-dimensional array and I want to access/modify an element in it using another array to specify the indices.

I figured out how to access a value, however I do not know how to modify the original value.

// Arbitrary values and shape
arr = [[[8, 5, 8],
        [9, 9, 9],
        [0, 0, 1]],

       [[7, 8, 2],
        [9, 8, 3],
        [9, 5, 6]]];

// Arbitrary values and length
index = [1, 2, 0];

// The following finds the value of arr[1][2][0]
// Where [1][2][0] is specified by the array "index"

tmp=arr.concat();

for(i = 0; i < index.length - 1; i++){
  tmp = tmp[index[i]];
}

// The correct result of 9 is returned
result = tmp[index[index.length - 1]];
  1. How can I modify a value in the array?

  2. Is there a better/more efficient way to access a value?

3 Answers 3

2

This is a classic recursive algorithm, as each step includes the same algorithm:

  • Pop the first index from indices.
  • Keep going with the array that the newly-popped index points to.

Until you get to the last element in indices - then replace the relevant element in the lowest-level array.

function getUpdatedArray(inputArray, indices, valueToReplace) {
  const ans = [...inputArray];
  const nextIndices = [...indices];
  const currIndex = nextIndices.shift();
  let newValue = valueToReplace;

  if (nextIndices.length > 0) {
    newValue = getUpdatedArray(
      inputArray[currIndex],
      nextIndices,
      valueToReplace,
    );
  } else if (Array.isArray(inputArray[currIndex])) {
    throw new Error('Indices array points an array');
  }

  ans.splice(currIndex, 1, newValue);
  return ans;
}

const arr = [
  [
    [8, 5, 8],
    [9, 9, 9],
    [0, 0, 1]
  ],

  [
    [7, 8, 2],
    [9, 8, 3],
    [9, 5, 6]
  ]
];
const indices = [1, 2, 0];
const newArr = getUpdatedArray(arr, indices, 100)
console.log(newArr);

Sign up to request clarification or add additional context in comments.

Comments

1

You can change the values in array like this,

arr[x][y][z] = value;

Does this help?

4 Comments

No. I know how to do that. My problem is doing that, only where x,y,z are specified using another array, index=[x,y,z].
You can do like this if you can be sure that the 3rd inner array length is 3 arr[index[0]][index[1]][index[2]] = value;
That would work, except I need it to work for any length.
@GalAbra has given the perfect answer I guess
0

I think what you're looking for is this:

arr[index[0]][index[1]][index[2]] = value;

I'm having trouble understanding what you're attempting to do in the second part of your example.

1 Comment

That's what I'm looking for, except, I need to it work for n dimensions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.