0

I have an array of arrays that I am trying to map. But I am having an issue with my mapping because mapping all indexes not just the one I want it to be mapping. I figured I can work my way around this by creating a new array of only of the data I am trying to map.

How can I push all index 2 into a new array? I have not been able to find an example of what I am attempting to do.

I am expecting an outcome of a new array that equals [231, 431, 481]

Here is an example of my code:

const array = [ ["name", 1, 231], [ "name", 2, 431], ["name", 3, 481] ] 

console.log(array)

let percentage = array.map(function (num, i) {
      return 100 * ((num - array[i - 1]) / (array[i - 1]));
    });

2

2 Answers 2

2

You can do this

const array = [ ["name", 1, 231], [ "name", 2, 431], ["name", 3, 481] ] 
const arrayNew = array.map(x => x[2])
// arrayNew === [231, 431, 481]
Sign up to request clarification or add additional context in comments.

Comments

0

Check the inline comments

const array = [
  ["name", 1, 231],
  ["name", 2, 431],
  ["name", 3, 481],
];

// If you know, there will be 3 elements in array 
console.log(array.map(([, , last]) => last));
console.log(array.map(({ 2: last }) => last));

// For any size of sub array, get the last element in map
console.log(array.map((arr) => arr[arr.length - 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.