Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Like Objects by Date in JavaScript Array

I have the following array:

var objArray = [
    { num: 1, date: '1/12/2017' },
    { num: 3, date: '1/12/2017' },
    { num: 7, date: '1/12/2017' },
    { num: 1, date: '1/13/2018' },
    { num: 3, date: '1/16/2018' },
    { num: 4, date: '1/16/2018' }
   ];

I want to combine those with same dates so that the output array looks like this:

var outputArr = [
    { num: 11, date: '1/12/2017' },
    { num: 1,  date: '1/13/2018' },
    { num: 7,  date: '1/16/2018' }
   ];

I'm adding all num with similar dates and creating a single new object.

I have a very large dataset of objects like this so I'm trying to reduce the amount of processing time for this.

I've got the arrays sorted by date so that it mirrors objArray.

For loops seems cumbersome since I'm taking the first date in the array and checking every other element in the array a la the following pseudo-code:

var newArr = [];
for(i = 0; i < objArray.length; i++) {
    for(j = 0; j < objArray.length; j++) {
        var tempArr = [];
        // check every date manually
        // add similar to new array
        tempArr.push({ similar items });
    }
    newArr.push(tempArr):
}

// Do another couple loops to combine those like arrays into another array    

There has to be a more elegant way to perform this than running multiple for loops.

Any suggestions would be appreciated.

like image 258
razorsyntax Avatar asked Aug 04 '26 08:08

razorsyntax


1 Answers

Simply use Array.reduce() to create a map and group values by date, Object.values() on the map will give you the desired output value:

let arr = [ { num: 1, date: '1/12/2017' }, { num: 3, date: '1/12/2017' }, { num: 7, date: '1/12/2017' }, { num: 1, date: '1/13/2018' }, { num: 3, date: '1/16/2018' }, { num: 4, date: '1/16/2018' } ];
   
let result = Object.values(arr.reduce((a, {num, date})=>{
  if(!a[date])
    a[date] = Object.assign({},{num, date});
   else
    a[date].num += num;
  return a;
 },{}));
 console.log(result);
like image 183
amrender singh Avatar answered Aug 06 '26 23:08

amrender singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!