1

I have an array called shopping list with elements containing the name of the product and its amount. Using the method .map I want to make a new array called product that only includes the product names from these elements. So that the new array would look like ['Milk', 'Coffee', 'Bananas', 'Bread'].

let shoppinglist = [ ['Milk', 1], ['Coffee', 2], ['Bananas'], ['Bread', 1] ];

const product = shoppinglist.map();

What do I put in after shoppinglist.map?

mntblnk
  • 77
  • 7

4 Answers4

2
let shoppinglist = [ ['Milk', 1], ['Coffee', 2], ['Bananas'], ['Bread', 1] ];

by using map

let result = shoppinglist.map(a => a[0]);

by using Array.from

let result1 = Array.from(shoppinglist, a => a[0]);

Hope this helps you !

Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0

For the record, your shoppingList array should be an object : {milk: 1, coffe: 2...}.
In your case, the map function needs to returns the first element of each sub array. So something like that.

let shoppinglist = [ ['Milk', 1], ['Coffee', 2], ['Bananas'], ['Bread', 1] ];

console.log(shoppinglist.map((data) => data[0]));
Nicolas
  • 8,077
  • 4
  • 21
  • 51
0

const products = shoppinglist.map(item => item[0])

Vlad Vidac
  • 978
  • 1
  • 10
  • 26
0

You can do it by returning the first element in the array using index 0.

let shoppinglist = [
  ['Milk', 1],
  ['Coffee', 2],
  ['Bananas'],
  ['Bread', 1]
];

const product = shoppinglist.map(item => item[0]);

console.log(product);
Nikhil
  • 6,493
  • 10
  • 31
  • 68