Categories
JavaScript Answers

How to sum values from an array of key-value pairs in JavaScript?

Spread the love

Sometimes, we want to sum values from an array of key-value pairs in JavaScript.

In this article, we’ll look at how to sum values from an array of key-value pairs in JavaScript.

How to sum values from an array of key-value pairs in JavaScript?

To sum values from an array of key-value pairs in JavaScript, we use the array reduce method.

For instance, we write

const myData = [
  ["2022-01-22", 0],
  ["2022-01-29", 0],
  ["2022-02-05", 0],
  ["2022-02-12", 0],
  ["2022-02-19", 0],
  ["2022-02-26", 0],
  ["2022-03-05", 0],
  ["2022-03-12", 0],
  ["2022-03-19", 0],
  ["2022-03-26", 0],
  ["2022-04-02", 21],
  ["2022-04-09", 2],
];
const sum = myData
  .map(([, val]) => val)
  .reduce((sum, current) => sum + current, 0);

console.log(sum);

to call myData.map to map the myData array into an array of values from the 2nd entry of each array.

Then we call reduce to return the partial sum of the array by adding sum to current and returning the sum.

0 is the initial value of sum.

current is the value being looped through

Conclusion

To sum values from an array of key-value pairs in JavaScript, we use the array reduce method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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