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]));
    });
stepheniok
  • 395
  • 3
  • 16
  • See [Map the first element of each array of an array of arrays in Javascript](https://stackoverflow.com/a/47415275/4642212). That would simply be `.map((subArray) => subArray[2])`, or `.map(({2: number}) => number)`, just [like with any other property](https://stackoverflow.com/q/19590865/4642212). What are you trying to calculate? – Sebastian Simon Mar 18 '21 at 16:40
  • im attempting to calculate the difference between the numbers. An annual percentage change – stepheniok Mar 18 '21 at 16:42

2 Answers2

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]
omeanwell
  • 1,847
  • 1
  • 10
  • 16
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]));
Siva K V
  • 10,561
  • 2
  • 16
  • 29