Skip to content
Advertisement

How to access the ith column of a Javascript Multidimensional Array?

For e.g if the array looks like this

var example = [[2, "Dwayne"], [4, "Mark"], [8, "Jeff"]];

I want to get the 2nd value of each array inside example array e.g values like this:

"Dwayne", "Mark", "Jeff"

Advertisement

Answer

You can use .map() to construct the desired output.

You must be careful about the index however i.e data in that index should exists in the input array otherwise you will get undefined.

const example = [[2, "Dwayne"], [4, "Mark"], [8, "Jeff"]];

const getValuesByIndex = (arr, i) => arr.map(a => a[i]);

console.log(getValuesByIndex(example, 1));
console.log(getValuesByIndex(example, 0));
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement