Javascript sum array of objects by key es6

You can reduce your data to a dictionary and then map it to an array like so

results = [ { unit: 5, date: '2015-12-04 00:01:00' },
      { unit: 10, date: '2015-12-04 00:01:00' },
      { unit: 5, date: '2015-12-04 00:31:00' },
      { unit: 9, date: '2015-12-04 00:31:00' },
      { unit: 5, date: '2015-12-04 01:01:00' },
      { unit: 10, date: '2015-12-04 01:01:00' },
      { unit: 10, date: '2015-12-04 01:31:00' },
      { unit: 5, date: '2015-12-04 01:31:00' },
      { unit: 10, date: '2015-12-04 02:01:00' },
      { unit: 5, date: '2015-12-04 02:01:00' },
      { unit: 5, date: '2015-12-04 02:31:00' },
      { unit: 9, date: '2015-12-04 02:31:00' },
      { unit: 5, date: '2015-12-04 03:01:00' },
      { unit: 9, date: '2015-12-04 03:01:00' },
      { unit: 5, date: '2015-12-04 03:31:00' },
      { unit: 10, date: '2015-12-04 03:31:00' },
      { unit: 10, date: '2015-12-04 04:01:00' },
      { unit: 5, date: '2015-12-04 04:01:00' }]

// first make an object with {date: unit} value as such
const newResults = results.reduce((acc, item) => ({
  ...acc,
  [item.date]: (acc[item.date] || 0) + item.unit
}) , {})

console.log(newResults)
/*
{
  "2015-12-04 00:01:00": 15,
  "2015-12-04 00:31:00": 14,
  "2015-12-04 01:01:00": 15,
  "2015-12-04 01:31:00": 15,
  "2015-12-04 02:01:00": 15,
  "2015-12-04 02:31:00": 14,
  "2015-12-04 03:01:00": 14,
  "2015-12-04 03:31:00": 15,
  "2015-12-04 04:01:00": 15
}
*/

// now if you want array representation for this you can do

const finalResult = Object.keys(newResults).map(key => ({date: key, unit: newResults[key]}))

console.log(finalResult)
/*
[
  {
    "date": "2015-12-04 00:01:00",
    "unit": 15
  },
  {
    "date": "2015-12-04 00:31:00",
    "unit": 14
  },
  {
    "date": "2015-12-04 01:01:00",
    "unit": 15
  },
  {
    "date": "2015-12-04 01:31:00",
    "unit": 15
  },
  {
    "date": "2015-12-04 02:01:00",
    "unit": 15
  },
  {
    "date": "2015-12-04 02:31:00",
    "unit": 14
  },
  {
    "date": "2015-12-04 03:01:00",
    "unit": 14
  },
  {
    "date": "2015-12-04 03:31:00",
    "unit": 15
  },
  {
    "date": "2015-12-04 04:01:00",
    "unit": 15
  }
]
*/

Sum a Property in an Array of Objects in JavaScript #

To sum a property in an array of objects:

  1. Call the reduce() method to iterate over the array.
  2. On each iteration increment the sum with the specific value.
  3. The result will contain the sum of the values for the specific property.

Copied!

const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; const sum = arr.reduce((accumulator, object) => { return accumulator + object.salary; }, 0); console.log(sum); // 👉️ 60

The function we passed to the Array.reduce() method gets invoked with each element (object) in the array.

The accumulator parameter gets an initial value of 0 because that's what we supplied as the second argument to the reduce method.

We increment the accumulator by the value of the salary property for each object in the array.

The reduce method returns the sum of the salary values of all objects in the array.

An alternative and perhaps simpler approach is to use the forEach method.

To sum a property in an array of objects:

  1. Initialize a sum variable, using the let keyword and set it to 0.
  2. Call the forEach() method to iterate over the array.
  3. On each iteration, increment the sum variable with the value of the object.

Copied!

const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; let sum = 0; arr.forEach(element => { sum += element.salary; }); console.log(sum); // 👉️ 60

The function we passed to the Array.forEach method gets called with each element in the array.

Notice that we declared the sum variable using the let keyword. We can't reassign variables declared using const.

On each iteration of the loop, we increment the value stored in the sum variable to get the total amount.

This approach is more readable and intuitive, especially if you're not used to how the reduce method works.

You can also achieve the same result by using a basic for loop.

Copied!

const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index].salary; } console.log(sum); // 👉️ 60

This code snippet achieves the same goal, however instead of the forEach method, we use a basic for loop.

Instead of accessing the element directly, we have to use the index of each iteration.

This is a bit indirect and cluttered, however most developers are used to reading for loops.

How do you sum multiple objects with the same key in an array?

How do you sum multiple objects with the same key in an array? First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'.

How do you sum values in array of objects?

To sum a property in an array of objects: Call the reduce() method to iterate over the array. On each iteration increment the sum with the specific value. The result will contain the sum of the values for the specific property.

How do you find the sum of all elements in an array in JavaScript?

function sumArray(array) { const ourArray = [1, 4, 0, 9, -3]; let sum = 0; ​ for (let i = 0; i < ourArray. length; i += 1) { ... .
function sumArray(array) { let sum = 0; ​ array. forEach(item => { sum += item; ... .
function sumArray(array) { let sum = 0; ​ /*loop over array and add each item to sum. */ for (const item of array) {.

How do you sum objects in JavaScript?

To sum the values of an object:.
Use the Object. values() method to get an array of the object's values..
Use the reduce() method to iterate over the array..
Add the current number to the accumulated number and return the result..