Slice through 2d array

Hello,

I have a 2d array such as a list of cars for sale:

[ 
  ["honda", "red", 1977, "USD 15k"],
  ["Volkswagen", "blue", 2005, "USD 22k"],
  ["Renault", "grey", 2012, "USD 30k"],
  ["Dodge", "yellow", 1985, "USD 10k"],
];

Is there a JS command allowing to create a new array with all colours? ([“red”, “blue”, “grey”, “yellow”]. I could do a loop but that is not elegant

kind regards and many thanks

Hi, you can use map to avoid the loop.

const cars = [
  ['honda', 'red', 1977, 'USD 15k'],
  ['Volkswagen', 'blue', 2005, 'USD 22k'],
  ['Renault', 'grey', 2012, 'USD 30k'],
  ['Dodge', 'yellow', 1985, 'USD 10k'],
];

const colors = cars.map(car => car[1]);

// ['red', 'blue', 'grey', 'yellow']
1 Like

Great, many thanks. It works!! It is such an elegant solution!

1 Like

You’re welcome :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.