2

I have a 2D array and want to access with another array e.g:

var arr = [['one','two'],['three','four']];
var arr2 = [1,1];

I want to have the value at arr[arr2[0]][arr2[1]]. Is there another way to get the value, because if I do it that way, the row would get extrem long and hard to read.

Something like:

arr[arr2]

I know that this don't work but is there something similar in JavaScript?

1
  • 1
    Why don't you use a loop in arr Commented Apr 13, 2018 at 13:46

5 Answers 5

1

You could reduce the array by using the indices, with a default array for not existent inner arrays.

function getValue(array, indices) {
    return indices.reduce((a, i) => (a || [])[i], array);
}

var array = [['one', 'two'], ['three', 'four']],
    indices = [1, 1];

console.log(getValue(array, indices));

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

Comments

0

Use reduce with try/catch to ensure that doesn't have values which will throw error (for example, arr2 = [1,1,2,3,4] )

function evaluate(arr1, arr2)
{
    try
    {
      return arr2.reduce( (a, c) => a[c], arr);
    }
    catch(e) {}
}

Demo

function evaluate(arr1, arr2) {
  try {
    return arr2.reduce((a, c) => a[c], arr)
  } catch (e) {}
}

var arr = [['one','two'],['three','four']];
var arr2 = [1,1];

console.log(evaluate(arr, arr2))

2 Comments

that solution uses an try ... catch concept for exception, which is not necessary for the task.
@NinaScholz You are right, yours is simpler. Since you had already posted that so I didn't changed mine.
0

Use arr[arr2[0]][arr2[1]] instead of arr[arr2]. Since, you only have two array values in your nested array for arr you can specify the index 0 and 1 for arr2 as a index of arr. Which is in the format arr[index1][index2]

var arr = [['one','two'],['three','four']];
var arr2 = [1,1];

console.log(arr[arr2[0]][arr2[1]]);

Comments

0

You could use Array#reduce on arr2 and pass arr as the initial array.

Demo

let arr = [['one','two'],['three','four']],
    arr2 = [1,1],
    res = arr2.reduce((a,c) => a[c], arr);

console.log(res);

Comments

0

This is an alternative:

A simple for-loop

var arr = [ ['one', 'two'], ['three', 'four'] ],
    indexes = [1, 1];

Array.prototype.getFrom = function(indexes) {
  var current;
  for (var index of indexes) current = current ? current[index] : this[index];
  return current;
}

console.log(arr.getFrom(indexes));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://codepen.io/egomezr/pen/dmLLwP.js"></script>

Comments

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.