Home > Web Front-end > JS Tutorial > How to Merge Duplicate Keys and Sum Their Values in JavaScript Object Arrays?

How to Merge Duplicate Keys and Sum Their Values in JavaScript Object Arrays?

DDD
Release: 2024-12-15 21:18:12
Original
970 people have browsed it

How to Merge Duplicate Keys and Sum Their Values in JavaScript Object Arrays?

Merge Duplicate Keys and Sum Values in JavaScript Object Arrays

When working with JavaScript arrays of objects, you may encounter duplicate keys that represent similar entities. To consolidate these duplicates and aggregate their corresponding values, you can leverage the following approach:

let objArr = [
  {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
  {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
  {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
  {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
];

// Utilize a Map to consolidate duplicate keys
let counts = objArr.reduce((prev, curr) => {
  let count = prev.get(curr.key) || 0;
  prev.set(curr.key, curr.val + count);
  return prev;
}, new Map());

// Convert the Map back to an array
let reducedObjArr = [...counts].map(([key, value]) => {
  return {key, value}
})

console.log(reducedObjArr);
Copy after login

This solution leverages a Map to accumulate values associated with duplicate keys. It iterates through the original array, extracting the key and value of each object. If the key already exists in the Map, it increments its corresponding value. Finally, it converts the Map back into an array of objects, providing the desired result.

The above is the detailed content of How to Merge Duplicate Keys and Sum Their Values in JavaScript Object Arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template