Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

merge values together in a 2d array

having a little bit of an issue trying to merge values in a 2d array.

For example:

const formatBids = 
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];

I want to sum up the 2nd param of the array if the first param are the same, so the end result being:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 [
   [4444, 10500],
   [4455, 500],
 ];

i have tried the following but its continually adding to itself producing the wrong results:

formatBids.map(bid => {
  const map = new Map([bid]);
  formatBids.forEach(arr => (arr[1] += map.get(arr[0]) ?? 0));
});

unsure the best way to tackle this. Ideas?

>Solution :

You could just use an Object as a sort of map and use the first item in an array as the key. Then you can convert it back to an Array using Object.entries(). Like so:

const formatBids = 
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];
 
const totals = {}

for (const bid of formatBids) {
  totals[bid[0]] = (totals[bid[0]] || 0) + bid[1];
}

console.log("as object:", totals, "as array:", Object.entries(totals));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading