Get Sum Of Array Object Values In JavaScript

To get sum of array object values in JavaScript, use any of these methods –

  1. Use a for loop to iterate over the array and add each element’s value to a sum variable.
  2. Use Array.reduce() to get the sum of array values.
  3. Use Array.forEach() to iterate over the array and add each element’s value to a sum variable.

Let’s look at each of these methods in detail below.

Get Sum Of Array Object Values In JavaScript

get sum of array object values in javascript

1. Use a for loop

Use a for loop to iterate over the array and add each element’s value to a sum variable.

This is the most basic method to get the sum of array values. You can use a for loop to iterate over the elements of the array and add their values to a sum variable as shown below:

function getSum(arr) {

 var sum=0;

 for(var i=0;i<arr.length;i++){

   sum+=arr[i].id;

 }

 return sum;

}

console.log(getSum([{id:1}, {id:2}, {id:3}])); // 6

In the above code, we have defined a getSum() function that takes an array as a parameter. This function uses a for loop to iterate over the elements of the given array and adds their id property values to a sum variable. Finally, it returns the sum.

2. Use Array.reduce()

Use Array.reduce() to get the sum of array values.

Array.reduce() is a built-in method that takes an array and reduces it to a single value by calling a callback function on each element in the array and storing the result in an accumulator variable.

We can use this method to get the sum of array values as shown below:

function getSum(arr) {

  return arr.reduce((acc, curr) => acc + curr.id, 0);

}

console.log(getSum([{id:1}, {id:2}, {id:3}])); // 6

In the above code, we have defined a getSum() function that takes an array as a parameter. This function uses Array.reduce() to iterate over the elements of the given array and adds their id property values to an accumulator variable. Finally, it returns the sum.

3. Use Array.forEach()

Use Array.forEach() to iterate over the array and add each element’s value to a sum variable.

This is similar to using a for loop, but with Array.forEach() you don’t have to explicitly create a loop variable and increment it.

function getSum(arr) {

var sum = 0;

arr.forEach(function(element) {

  sum += element.id;

});

return sum;

}

console.log(getSum([{id:1}, {id:2}, {id:3}])); // 6

In the above code, we have defined a getSum() function that takes an array as a parameter. This function uses Array.forEach() to iterate over the elements of the given array and adds their id property values to a sum variable. Finally, it returns the sum.

These are some of the methods you can use to get sum of array object values in JavaScript. Choose the method that best suits your needs.

Leave a Reply