Follow the Map explainer


#1

The aim of this puzzle: Complete the arrow function so that it takes an item and returns its price.

Walkthrough of the solution: The groceries variable is an array of objects. Each object has a .name and .price property. To get an array with just the names, .map() and an arrow function are used. .map() is similar to .forEach() except it creates a new array instead of changing the original array.

To get an array of just the price values, we want to .map() each item to its price. We can make an arrow function that does that. It will use item as an input parameter between its parentheses (). Then inside the curly brackets {}, it should return item.price.

That whole arrow function is the argument of the .map() method. The .map() will run each element of the groceries array through that function and then return a new array of all the results. That new array gets stored inside of the prices variable so we can log it to the console.

Sample code solution:
(Tap below to reveal)

import { groceries } from 'grasshopper.store';

let names = groceries.map((item) => {
  return item.name;
});
let prices = groceries.map((item) => {
  return item.price;
});

console.log('Names: ' + names);
console.log('Prices: ' + prices);

JavaScript Concepts: Code Block (arrow function), console.log(), .map()


#2