Working with map()

Caroline Cah
Caroline Cah

If you're ever going to work with data consisting of multiple elements you will find the map function very useful.

map() creates a new array by calling a function for every array element.

map() does not change the contents of the original array.

How can I use it?

Extracting subsets

For example, extracting the property item from an array such as:

const arrayObject = [
  {record : "12345", item: "Keys"},
  {record : "56789", item: "Values"},
  {record : "101112", item: "Model"}

You can use a map function to create a new array only with the record and one array for all items.

const records = => obj.record); 
const items = => obj.item);


Result of console.log:

["12345", "56789", "101112"]


Result of console.log:

["Keys", "Values", "Model"]

Calculating Values

Imagine you have an array of product objects, and you want to calculate the total price for each product (price * quantity). You could do this by map() and multiplying the products price with the quantity.

const products = [
  { name: "Book", price: 10, quantity: 2 },
  { name: "Pen", price: 5, quantity: 3 },
  { name: "Notebook", price: 20, quantity: 1 }

const totalPrice = => product.price * product.quantity);


Result of console.log:

[20, 15, 20]

Using map() together with filter()

Sometimes you might want to filter out your array elements. This is where you can combine the filter() method together with creating a new array of the filtered result.

const people = [
  { name: "Alice", age: 17 },
  { name: "Bob", age: 20 },
  { name: "Charlie", age: 22 },
  { name: "Diana", age: 15 }

const greeting = => {
  if (person.age >= 18) {
    return `Hello, ${}! Ready to start adulting? #WhyIsEverythingSoExpensive`;
  } else {
    return `Hey, ${}! Still enjoying the 'no bills' life? #LivingTheDream`;


Result of console.log(greeting)

"Hey, Alice! Still enjoying the 'no bills' life? #LivingTheDream",
"Hello, Bob! Ready to start adulting? #WhyIsEverythingSoExpensive",
"Hello, Charlie! Ready to start adulting? #WhyIsEverythingSoExpensive",
"Hey, Diana! Still enjoying the 'no bills' life? #LivingTheDream"]
More posts