How to Sum the Values of an Object in JavaScript

Photo by Jess Bailey on Unsplash

How to Sum the Values of an Object in JavaScript

ยท

2 min read

Hello Coders! welcome or welcome back to the blog. I'm back again with another coding challenge but this time around, it's from the object part of javascript. Here's a challenge I came across and would like to solve with y'all:

Sum Object Properties: We have an object storing the salaries of our team: Write the code to sum all salaries and store it in the variable 'sum'.The result should be 390. If salaries are empty, the result should be 0.

I initially tried using the for in loop method and it returned 0 only because I approached this problem as I would for an array unknowingly to me that the same method(s) could be used but there's a slight difference with their syntax. Anyhoo, here's my solution:๐Ÿ‘‡๐Ÿพ

  1. The first approach would be declaring a sum variable using the let keyword and set it to 0 just so that we would be able to reassign it.

  2. Next, I decided to use the for...in loop to iterate over the object's properties and on each iteration, increment the sum variable with the current value. The for...in loop iterates over the object's properties and allows us to access each value and once the loop has iterated over all of the object's properties we have the sum of the values.

    Here's what I mean๐Ÿ‘‡๐Ÿพ

let salaries ={
    John: 100,
    Ann: 160,
    Pete: 130,
 }

let sum = 0;

 for (const key in salaries) {
   sum += salaries[key];
 }

console.log(sum); // 390

There's another method to approach this and it's called the ** reduce method**.

const values = Object.values(salaries);

const sum = values.reduce((accumulator, value) => {
  return accumulator + value;
}, 0);

console.log(sum); // 390

This is all from today's challenge, hopefully, this makes sense after going through it. Let me know what you think in the comment section and of course, share your thoughts and other possible solutions.

Write y'all soon!

ย