Just Learn Code

Efficiently Summing Up Values in JavaScript Arrays with Reduce Method

Managing arrays in JavaScript can be tough, especially when dealing with objects as elements. Whether you’re working with a list of books, a collection of shoes, or even kitchen utensils, it’s always helpful to know how to sum up certain properties within an array.

This article will teach you how to use the reduce method to sum up values in an array of objects. Additionally, we will go over how to filter elements that you don’t want to include in your sum, as well as how to perform multiple operations using quantity and multiplication.

In the end, you will have a solid understanding of how to sum up values in an array of objects with ease.

Using the reduce method

The reduce() method is a built-in function in JavaScript that applies an operation against an accumulator and each element in the array (from left to right) to reduce it to a single value. The reduce method takes two parameters: the first is a callback function, and the second is an initial value.

The callback function inside the reduce method is called on each element of the array. The callback function takes two parameters: the accumulator and the current element in the array.

The initial value parameter is used as the initial value of the accumulator. Here’s a basic example that sums up all the values in an array of objects:

“`

const items = [

{ name: ‘Book’, price: 60 },

{ name: ‘Shoes’, price: 80 },

{ name: ‘Whisk’, price: 10 }

];

const totalPrice = items.reduce((accumulator, item) => accumulator + item.price, 0);

console.log(totalPrice); // 150

“`

In this example, the reduce method is used to sum up the price of all items in the items array.

The reduce method starts with an initial value of zero, which is the second parameter passed to the method. As the reduce method goes through each element in the array, it adds up the price property of each object to the accumulator and returns the total sum at the end.

Performing multiple operations

Sometimes you’ll want to perform more than just a simple addition operation. For example, you might want to find the total cost of a certain number of items in an array, or the discount price if each item is discounted by a certain percentage.

In these cases, you can use the accumulator as a way to perform multiple operations. For instance, you can use the quantity and multiplication to find the total cost of ten books in the below example:

“`

const items = [

{ name: ‘Book’, price: 60 },

{ name: ‘Shoes’, price: 80 },

{ name: ‘Whisk’, price: 10 }

];

const totalCost = items.reduce((accumulator, item) => {

if (item.name === ‘Book’) {

accumulator += item.price * 10;

}

return accumulator;

}, 0);

console.log(totalCost); // 600

“`

In this example, the reduce method is used to sum up the total cost of ten books, which are identified by their name property.

Instead of just adding each item price, we’ve multiplied the item price by ten to account for the quantity and added the result to the accumulator. Note that we’re not just using the simple addition operator anymore, but instead using multiplication.

By using conditionals within the reduce method, you can selectively perform different operations on each item within the array.

Filtering the array before using reduce

What if you want to filter certain items in the items array before using the reduce method? This can be done by using the filter method beforehand.

For instance, let’s say you want to sum up only the prices of items that cost more than $50. You can use the filter method before using the reduce method like so:

“`

const items = [

{ name: ‘Book’, price: 60 },

{ name: ‘Shoes’, price: 80 },

{ name: ‘Whisk’, price: 10 }

];

const expensiveItems = items.filter(item => item.price > 50);

const totalPrice = expensiveItems.reduce((accumulator, item) => accumulator + item.price, 0);

console.log(totalPrice); // 140

“`

In the above example, we’re first filtering the items array so that only items with a price property greater than 50 are included in the new expensiveItems array.

Then, we’re using the reduce method to sum up the price property of the objects in expensiveItems to get the total price of the expensive items.

List of Items

Now that we’ve discussed how to sum up values in an array of objects with the reduce method, let’s go over an example array of items. Our example array of items contains three objects:

“`

const items = [

{ name: ‘JavaScript book’, price: 60 },

{ name: ‘UGG Women’s Hazel Ankle Boot’, price: 175 },

{ name: ‘OXO Good Grips 11-Inch Balloon Whisk’, price: 10 }

];

“`

This array contains a list of three items: a JavaScript book, UGG Women’s Hazel Ankle Boot, and an OXO Good Grips 11-Inch Balloon Whisk, with their respective prices.

Price for each Item

Now that we have our list of items in the items array, let’s take a closer look at the price for each item. The JavaScript book has a price of $60, the UGG Women’s Hazel Ankle Boot has a price of $175, and the OXO Good Grips 11-Inch Balloon Whisk has a price of $10.

If we wanted to find the total price of all items in the array, we could use the reduce method we discussed earlier:

“`

const totalPrice = items.reduce((accumulator, item) => accumulator + item.price, 0);

console.log(totalPrice); // 245

“`

In this example, we’re using the reduce method to sum up the price property of all objects in the items array. The initial value of the accumulator is 0, and we’re adding the price of each item to the accumulator.

The resulting total price of all items in the array is $245. Conclusion:

We’ve learned how to efficiently sum up values in an array of objects with the reduce method.

Whether you’re trying to do a simple addition, perform multiple operations, or filter the array before summing values, the reduce method makes it easy to achieve your desired result. Always keep in mind the initial value parameter, which sets the starting value for the accumulator, and the callback function, which is where all the computation happens.

Remember to take advantage of conditionals and filter methods to selectively and efficiently target elements within your array. Happy coding!

Expansion:

In Part 1, we discussed how to sum up values in an array of objects using the reduce method.

We also looked at how to filter certain items in an array and perform multiple operations using the accumulator. In this second part, we’ll explore more deeply how the initial value parameter works and how to perform multiple operations with quantity data using the reduce method.

Initial Value

The initial value parameter in the reduce method is useful because it allows you to set the initial value of the accumulator. This value is the value that the accumulator holds before any element of the array is processed by the callback function.

The initial value can be any data type such as a number, string, or object. However, the initial value must be set in the second parameter of the reduce method.

If you don’t provide an initial value, then the first object of the array will be used as the initial value. If the first element of the array is not an object, the reduce method will use the second element instead of the first.

Here’s an example of how to provide an initial value:

“`

const numbers = [1, 2, 3, 4];

const initialValue = 0;

const sum = numbers.reduce((accumulator, currentValue) =>

accumulator + currentValue, initialValue);

console.log(sum); // 10

“`

In this example, we’ve set an initial value of 0 in the second parameter of the reduce method. Therefore, the accumulator starts with a value of 0 and adds each element of the numbers array to it.

Accumulating Values

The accumulator in the reduce method is a variable that holds the value accumulated from each element in the array. You can use the accumulator to hold a sum of values, a total quantity, or any other variable that you want to modify throughout the array.

By using the accumulator, you can perform operations on elements in the array and accumulate the results. For instance, let’s say you have an array of numbers representing the amount of money received from different clients, and you want to sum them up:

“`

const moneyReceived = [10, 20, 30, 40];

const totalAmount = moneyReceived.reduce((accumulator, currentValue) =>

accumulator + currentValue, 0);

console.log(totalAmount); // 100

“`

In this example, we’ve initialized the accumulator with an initial value of 0.

The reduce method then uses the accumulator to store the sum of each element in the array. By the end of the function, the total amount of money received is stored in the accumulator and returned as the result.

Quantity Data

The reduce method can also be used with quantity data. For example, let’s say that you have an array of objects representing products in a store, and you want to calculate the total cost of purchasing a certain quantity of each product.

“`

const products = [

{ name: ‘Shoe’, price: 50 },

{ name: ‘Socks’, price: 10 },

{ name: ‘Hat’, price: 20 }

];

const shoppingCart = [

{ name: ‘Shoe’, quantity: 1 },

{ name: ‘Socks’, quantity: 3 },

{ name: ‘Hat’, quantity: 2 }

];

const totalCost = shoppingCart.reduce((accumulator, currentValue) => {

const product = products.find(product => product.name === currentValue.name);

return accumulator + (product.price * currentValue.quantity);

}, 0);

console.log(totalCost); // 100

“`

In this example, the reduce method is used to calculate the total cost of the products purchased, given the quantity data for each product. We’ve defined two arrays: the products array, which specifies the name and price of each product, and the shoppingCart array, which specifies the name and quantity of each product being purchased.

The reduce method takes a callback function that uses the accumulator and the current value of shopping cart items (currentValue) to calculate the total cost. We’re using the find method to search products array for each item’s name in the shopping cart, and then we calculate the total price by multiplying the price of the product and the quantity of the item in the shopping cart.

Using Accumulator

In Part 1, we looked at how the accumulator can be used to perform multiple operations. Similarly, we can use the accumulator to perform multiple calculations on each element in the shoppingCart array.

“`

const shoppingCart = [

{ name: ‘Shoe’, quantity: 1 },

{ name: ‘Socks’, quantity: 3 },

{ name: ‘Hat’, quantity: 2 }

];

const totalCost = shoppingCart.reduce((accumulator, currentValue) => {

const product = products.find(product => product.name === currentValue.name);

accumulator.totalQuantity += currentValue.quantity;

accumulator.totalPrice += (product.price * currentValue.quantity);

return accumulator;

}, { totalPrice: 0, totalQuantity: 0 });

console.log(totalCost); // {totalPrice: 100, totalQuantity: 6}

“`

In this example, we’re using the accumulator to store the total quantity and total price of items in the shopping cart. We’re initializing the accumulator with an object in the second parameter of the reduce method that has two properties: totalPrice and totalQuantity.

Then, in the callback function, we’re adding the quantity of each item in the shopping cart to the totalQuantity property of the accumulator and adding the price of each item to the totalPrice property. In the end, the reduce method returns the object with the total price and total quantity properties.

Conclusion:

In this article, we’ve explored the reduce method in JavaScript and its various applications. Whether you’re dealing with quantity data or performing multiple operations, the reduce method is a powerful technique that can save a lot of time and effort.

By using an initial value parameter to set the starting value for the accumulator, and by using the accumulator to accumulate values throughout the array, you can efficiently perform calculations and retrieve useful data from an array. Expansion:

In Part 1, we introduced the reduce method and its use in summing up values in an array of objects.

In Part 2, we talked about how to use the reduce method with quantity data and how to perform multiple operations on an array of objects. In this section, we will focus on using the filter method to filter the array before using the reduce method.

Purpose of Filtering

The filter method in JavaScript is a built-in method that creates a new array with all elements that pass a specific test. The filter method is useful when you want to extract a certain subset of data from an array that meets certain criteria.

One advantage of using the filter method is that it allows you to create a new array containing only the objects that you’re interested in before using the reduce method. This is especially helpful when dealing with a large array containing many objects, but you only need a subset of that data for your computation.

For example, let’s say you have a list of objects representing products in a store and you want to calculate the total cost of only the books in the store:

“`

const products = [

{ name: ‘JavaScript book’, price: 60 },

{ name: ‘UGG Women’s Hazel Ankle Boot’, price: 175 },

{ name: ‘OXO Good Grips 11-Inch Balloon Whisk’, price: 10 }

];

const books = products.filter(product => product.name === ‘JavaScript book’);

const totalCost = books.reduce((accumulator, currentValue) =>

accumulator + currentValue.price, 0);

console.log(totalCost); // 60

“`

In this example, we’ve used the filter method to create a new array, called books, that contains only the objects with a name property equal to ‘JavaScript book’. Then, we’ve used the reduce method to calculate the total cost of only the books.

This is more efficient than using the reduce method on the entire array of products.

Filter Condition

When using the filter method to create a new array, it’s important to define a condition that the elements in the array should satisfy. In the previous example, we used the filter method with a condition that checked if the name of the product is ‘JavaScript book’.

We could use a similar syntax with more complex conditions, such as checking for the price greater than 50. “`

const expensiveProducts = products.filter(product => product.price > 50);

const totalCost = expensiveProducts.reduce((accumulator, currentValue) =>

accumulator + currentValue.price, 0);

console.log(totalCost); // 235

“`

In this example, we’ve used the filter method to create a new array called expensiveProducts that only contains products with a price greater than 50.

We’re then using the reduce method to calculate the total cost of only the expensive products. Once again, this approach is more efficient than using the reduce method on the entire array of products.

Another way to use the filter method is to provide a separate function to test each element in the array. This function will be applied to each element, and only the elements that pass the function’s test will be included in the output array.

Here’s an example:

“`

function isEven(element) {

return element % 2 === 0;

}

const filteredArray = [1, 2, 3, 4, 5, 6, 7, 8].filter(isEven);

console.log(filteredArray); // [2, 4, 6, 8]

“`

In this example, we’ve defined a function called isEven that returns true if the element is even, and false if the element is odd. We’ve then used the filter method to create a new array that only contains the even elements from the original array.

Conclusion:

The filter method is a powerful tool that can help you extract a

Popular Posts