0

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"
1
  • 2
    example.map(v => v[1])? Commented Jan 14, 2021 at 7:24

4 Answers 4

2

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

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

Comments

0

There are 2 parts to complete it:

  1. You can use map to create a new array from the original array without mutating its data.
  2. use 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);

Comments

0

You can use a for-loop to iterate the array.

const example = [
  [2, "Dwayne"],
  [4, "Mark"],
  [8, "Jeff"]
];
for (let i = 0; i < example.length; i++) {
  console.log(example[i][1]);
}

In this case i selects the array within the array and 1 returns index 1 (the name).

Comments

0

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

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.