CodewCaro.

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 = arrayObject.map(obj => obj.record); 
const items = arrayObject.map(obj => obj.item);

console.log(records);

Result of console.log:


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

console.log(items);

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 = products.map(product => product.price * product.quantity);

console.log(totalPrice);

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 = people.map(person => {
  if (person.age >= 18) {
    return `Hello, ${person.name}! Ready to start adulting? #WhyIsEverythingSoExpensive`;
  } else {
    return `Hey, ${person.name}! Still enjoying the 'no bills' life? #LivingTheDream`;
  }
});

console.log(greeting);

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