Categories
JavaScript Answers

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

Spread the love

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

For instance, we write

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

to call myData.map with a callback that gets the 2nd value from each nested array.

Then we call reduce to return the sum of sum and current and set the initial sum to 0.

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 *