Just Learn Code

Efficiently Summing Values of Object Arrays in JavaScript

Summing the values of an array of objects is a common operation in programming, and there are several ways to accomplish it. Two of the most commonly used methods are the reduce() method and the combination of map() and reduce() methods.

In this article, we’ll explore these techniques in detail, and learn how to implement them in our own code.

Reduce() Method

The reduce() method is a built-in function in JavaScript that is used to reduce an array to a single value. The function takes two arguments – the first is an accumulator, which stores the running total, and the second is the current element of the array being processed.

The reduce() method performs an operation on the accumulator and current element, and then returns the updated value of the accumulator. This process continues until all the elements of the array have been processed, and the final value of the accumulator is returned.

To sum the values of an array of objects using the reduce() method, we first need to define the initial value of the accumulator. For example, if we have an array of objects, each containing a “value” property, we can initialize the accumulator to 0, like this:

“`

const arr = [

{value: 1},

{value: 2},

{value: 3},

{value: 4},

{value: 5},

];

const sum = arr.reduce((acc, cur) => {

return acc + cur.value;

}, 0);

console.log(sum); // Output: 15

“`

In this example, the reduce() method takes two arguments – the first is a callback function that defines the operation to perform on the accumulator (acc) and current element (cur), and the second is the initial value of the accumulator (0).

Inside the callback function, we simply add the value of the current element to the accumulator, and return the new value of the accumulator.

Implementing reduce() method on an object array

The reduce() method is not just restricted to arrays of primitive values. We can also use it to sum the values of an array of objects containing more than one property.

For example, if we have an array of objects representing sales data, with each object containing a “sales” property and a “year” property, we can sum the sales for each year like this:

“`

const salesData = [

{year: 2019, sales: 100},

{year: 2020, sales: 200},

{year: 2021, sales: 300},

];

const salesByYear = salesData.reduce((acc, cur) => {

const year = cur.year;

const sales = cur.sales;

if(!acc[year]) {

acc[year] = 0;

}

acc[year] += sales;

return acc;

}, {});

console.log(salesByYear); // Output: {2019: 100, 2020: 200, 2021: 300}

“`

In this example, we initialize the accumulator to an empty object, {}. Inside the callback function, we use the year property of each object as the key in the accumulator object, and store the sales for that year as the value.

If the key doesn’t exist in the accumulator object yet, we create it and set its value to 0. At the end of each iteration, we return the updated accumulator object.

Map() and

Reduce() Methods

The combination of map() and reduce() methods is another way to sum the values of an array of objects. The map() method is used to transform each element of an array into a new value, while the reduce() method is used to reduce the transformed values to a single value.

This technique is particularly useful when we want to filter out certain elements from the array before summing their values.

Using the map() function to change the values of each element in an array

To demonstrate how to use map() and reduce() in combination to sum the values of an array of objects, let’s start with a simple example. Suppose we have an array of objects representing the grades of a student in different subjects, and we want to find the total of all the grades except for the subject “PE”.

Here’s how we can do it:

“`

const grades = [

{subject: ‘Math’, grade: 90},

{subject: ‘Science’, grade: 80},

{subject: ‘PE’, grade: 70},

{subject: ‘History’, grade: 85},

];

const filteredGrades = grades

.filter(g => g.subject !== ‘PE’)

.map(g => g.grade);

const sum = filteredGrades.reduce((acc, cur) => acc + cur, 0);

console.log(sum); // Output: 255

“`

In this example, we first use the filter() method to remove the object with the subject “PE” from the array. Then we use the map() method to extract the “grade” property of each object and create a new array containing only the grades.

Finally, we use the reduce() method to sum the values of the new array and get the total.

Using filter() function to remove values that do not fit a certain category

The filter() method is particularly useful when we want to include only certain elements from the array in the sum. For example, let’s say we have an array of objects representing expenses, with each object containing a “category” property and an “amount” property.

We want to sum the amounts for all expenses in the “Food” category. Here’s how we can do it:

“`

const expenses = [

{category: ‘Food’, amount: 50},

{category: ‘Transportation’, amount: 30},

{category: ‘Food’, amount: 70},

{category: ‘Entertainment’, amount: 20},

{category: ‘Food’, amount: 40},

];

const foodExpenses = expenses

.filter(e => e.category === ‘Food’)

.map(e => e.amount);

const sum = foodExpenses.reduce((acc, cur) => acc + cur, 0);

console.log(sum); // Output: 160

“`

In this example, we first use the filter() method to select only the objects with the “Food” category, and then use the map() method to extract the “amount” property of each object and create a new array containing only the amounts.

We finally use the reduce() method to sum the values of the new array and get the total.

Using the reduce() function to obtain the sum of the array

In summary, using the reduce() method or the combination of map() and reduce() methods are two effective ways to sum the values of an array of objects in JavaScript. The reduce() method is a powerful way to reduce an array to a single value, while the map() and reduce() methods can be used together to filter out certain elements from the array before summing their values.

By mastering these techniques, we can write more efficient and concise code that performs complex operations on arrays of objects with ease. In this article, we explored two popular ways to sum the values of an array of objects in JavaScript – the reduce() method and the combination of map() and reduce() methods.

We learned how to implement these techniques and saw examples of how they can be used to filter out certain elements or perform operations on arrays with multiple properties. By mastering these methods, developers can write more efficient and concise code that performs complex operations on arrays of objects with ease.

As a final thought, it’s important to remember that properly summing the values of an array of objects is a critical skill for any JavaScript developer, and one that can save time and resources in a wide variety of applications.

Popular Posts