JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to reduce an array of objects in JavaScript?

In an array of objects, each element is an object. An object has properties and methods. To access a property or method of an object, you have to first access the object using zero-based indexing and then use dot notation to access that property or method.

Suppose you have a shoppingCart array. Each element of this array represents a product placed by the customer into the cart.

let shoppingCart = [
  {
    pid:214831,
    name:'Google Nest Cam Indoor',
    price:129.99,
    quantity:1
  },
  {
    pid:324567,
    name:'Amazon Blink Mini',
    price:34.99,
    quantity:2
  },
  {
    pid:859012,
    name:'Ring Video Doorbell',
    price:89,
    quantity:2
  }
];

To access the price of Amazon Blink Mini, you have to know its index position, which is 1 and then use dot notation to access its price.

shoppingCart[1].price

In this tutorial, you will learn how to reduce an array of objects using the array reduce() method. Suppose you want to find the total price of all the products inside the shoppingCart array, then go through the following process:

let shoppingCart = [
  {
    pid:214831,
    name:'Google Nest Cam Indoor',
    price:129.99,
    quantity:1
  },
  {
    pid:324567,
    name:'Amazon Blink Mini',
    price:34.99,
    quantity:2
  },
  {
    pid:859012,
    name:'Ring Video Doorbell',
    price:89,
    quantity:2
  }
];
let totalPrice = shoppingCart.reduce((acc, cur)=>{
  return acc + cur.price*cur.quantity;
}, 0);
console.log(totalPrice);

Here, cur represents the current object being processed.

In this way, you can reduce the array of objects. To learn more about the reduce() method, visit What is the array reduce() method in JavaScript?

Recommended Posts