How to Sum the Values of an Object in JavaScript-Code Examples

Radu TM

How to Sum the Values of an Object in JavaScript

JavaScript by Radu TM June 21, 2022

// How to sum the values of an object in JavaScript

// Declare an object
let obj = {
  a: 1,
  b: 2,
  c: 3
};

// Use `Object.values()` to get an array of the object's values
let values = Object.values(obj);

// Use `Array.reduce()` to get the sum of the array's values
let sum = values.reduce((acc, cur) => acc + cur, 0);

// 💡 The `0` in `reduce()`'s second argument is the initial value 
// for the accumulator. If omitted, it defaults to the first value 
// in the array.

console.log(sum); // 6

0

19.997

How to Sum the Values of an Object in JavaScript

JavaScript by Radu TM June 21, 2022

// define a function that takes in an object as input and outputs the sum of all the values
const sumValuesOfAnObject = obj => {
  // create a variable to store the sum
  let sum = 0;
  // loop through each key in the object
  for (let key in obj) {
    // add the value of the current key to the sum
    sum += obj[key];
  }
  // return the sum
  return sum;
};

const myObj = {
  a: 1,
  b: 2,
  c: 3
};

console.log(sumValuesOfAnObject(myObj)); // 6

0

19.997

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories