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"
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; }
There are 2 parts to complete it:
map to create a new array from the original array without mutating its data.Destructuring_assignment to destruct each item. After that, you can get the item you want.var example = [[2,"Dwayne"],[4,"Mark"], [8,"Jeff"]];
var result = example.map(([item1, item2]) => item2);
console.log(result);
As already answered, to store the resultant array in the code you can use map. On the other hand, take into account you can access the different dimensions of your array with the corresponding dimension index [index], like this:
const example = [
[2, "Dwayne"],
[4, "Mark"],
[8, "Jeff"]
];
for (let i = 0; i < example.length; i++) {
console.log(example[i][1]);
}
example.map(v => v[1])?