sum of array objects

Sum of the array of objects using javascript

In this blog, we will learn how to add an array of objects using javascript. In this, we will add the array of objects using different ways

Firstly we will define the array of objects with properties playerName, and goals. we will use different methods to add the goals of all objects in the array.

Using Foreach method

// Array of objects with playerName and goals as a property
const array = [
  { playName: "One", goals: 3 },
  { playName: "Two", goals: 2 },
  { playName: "Three", goals: 1 },
];

// Method 1: Using ForEach

let totalGoals = 0;

array.forEach((item) => {
  totalGoals = totalGoals + item.goals;
});

// Output
// 6

In the above code, we are defining a variable that will store the sum and we are initializing it with 0.

Then we will iterate through the array using the Array.forEach() method. Add the goals of each element to the sum variable. Once the array is completely iterated we will have the sum of the goals of an array

Using Reduce method

// Array of objects with playerName and goals as a property
const array = [
  { playName: "One", goals: 3 },
  { playName: "Two", goals: 2 },
  { playName: "Three", goals: 1 },
];

// Method 2: Using Reduce

const totalGoals = array.reduce((total, item) => total + item.goals, 0);

// Output
// 6

In this type, we are using Array.reduce() method to find the sum of the array of objects. For the reduce method, we are passing the arrow functions as the first argument, and for the second argument, we are initializing the total value as 0 and passing it.

The arrow function will take total and current Items as params. It returns the sum of the total and goals of the current item. After each iteration is completed the current item’s goals are added to the total variable. So, at the end of reduce method, we will get the total goals.

Using the Map Reduce method

// Array of objects with playerName and goals as a property
const array = [
  { playName: "One", goals: 3 },
  { playName: "Two", goals: 2 },
  { playName: "Three", goals: 1 },
];

// Method 3: Using Map Reduce

const totalGoals = array
  .map((item) => item.goals)
  .reduce((total, cur) => total + cur);

// Output
// 6

In this way, we are using Array.map() method to convert an array of objects to an array that will have goals as its elements.

Once the array is converted, we use Array.reduce() method adds all the goals, which are already discussed in the above type.

Leave a Comment

Your email address will not be published. Required fields are marked *