Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum values in array by specific object key?

I have an array of js objects which look like this:

var objArr = [
     {"Country": "US", "City": "MyCity1", "2017-07-12": "1", "2017-07-13": "2"},
     {"Country": "US", "City": "MyCity2", "2017-07-12": "2", "2017-07-13": "2"},
     {"Country": "CN", "City": "MyCity1", "2017-07-12": "5", "2017-07-13": "7"},
     {"Country": "CN", "City": "MyCity2", "2017-07-12": "5", "2017-07-13": "7"}
   ]

I wanna create a new array where the country is unique, but also the dates should be summed.

{"Country": "US", "2017-07-12":  "3", "2017-07-13": "4"},
{"Country": "CN", "2017-07-12": "10", "2017-07-13": "14"}
            ^^^^                ^^^^                ^^^^   

I have problems getting my head around it. Do I have to filter first, reduce it somehow, remap it,... I've no idea to start? Any help would be appreciated, thank you!

like image 777
Jan Avatar asked Oct 15 '22 05:10

Jan


1 Answers

Use Array.reduce, check if an object with the current country exists, if it does, loop through the Object.keys to update the values, if not, push a new one :

EDIT : If you don't want City you can destructure it {City, ...curr}

var objArr = [
  { Country: "US", City: "MyCity1", "2017-07-12": "1", "2017-07-13": "2" },
  { Country: "US", City: "MyCity2", "2017-07-12": "2", "2017-07-13": "2" },
  { Country: "CN", City: "MyCity1", "2017-07-12": "5", "2017-07-13": "7" },
  { Country: "CN", City: "MyCity2", "2017-07-12": "5", "2017-07-13": "7" }
];

var result = objArr.reduce((acc, {City, ...curr}) => {
  const ndx = acc.findIndex(e => e.Country === curr.Country);
  if (ndx > -1) {
    const [country, ...keys] = Object.keys(curr);
    keys.forEach(k => {
      acc[ndx][k] = +acc[ndx][k] + +curr[k];
    });
  } else {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(result);
like image 137
Taki Avatar answered Nov 01 '22 14:11

Taki