Teletubbie
Teletubbie

Reputation: 23

Access to 2D array with another array

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?

Upvotes: 2

Views: 59

Answers (5)

Ele
Ele

Reputation: 33726

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>

Upvotes: 0

Kristianmitk
Kristianmitk

Reputation: 4778

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);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

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));

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

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

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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

Upvotes: 0

Related Questions