ayordy67 ayordy67 - 2 months ago 20
TypeScript Question

Combine and add 2 arrays typescript, lodash, underscore

I have an array of objects that looks like this:

[
{date: '2016-09-10', 'Post': 5, 'Pickup': 2},
{date: '2016-09-11', 'Post': 8, 'Pickup': 2},
{date: '2016-09-12', 'Post': 0, 'Pickup': 2},
{date: '2016-09-12', 'Post': 3, 'Pickup': 0},
{date: '2016-09-13', 'Post': 1, 'Pickup': 2},
{date: '2016-09-13', 'Post': 1, 'Pickup': 0},
]


I need to combine the objects by date and add post+post and pickup+pickup to look like this:

[
{date: '2016-09-10', 'Post': 5, 'Pickup': 2},
{date: '2016-09-11', 'Post': 8, 'Pickup': 2},
{date: '2016-09-12', 'Post': 3, 'Pickup': 2},
{date: '2016-09-13', 'Post': 2, 'Pickup': 2},
]


I would prefer lodash and/or underscore.

Thanks.

I started with 2 arrays like this:

pickup = [
{date: '2016-09-11', 'Post': 8, 'Pickup': 2},
{date: '2016-09-12', 'Post': 3, 'Pickup': 0},
{date: '2016-09-13', 'Post': 1, 'Pickup': 0},
]

post = [
{date: '2016-09-10', 'Post': 5, 'Pickup': 2},
{date: '2016-09-12', 'Post': 0, 'Pickup': 2},
{date: '2016-09-13', 'Post': 1, 'Pickup': 2},
]


I used
data = _.unionBy( post, pickup, 'date' );


and
_.uniqBy( data, 'date' );

Answer

You could use reduce and create a new object in the resulting array for new dates, or just add to the Posts and Pickups if there already is one:

var result = _.reduce(array, function (memo, el) {
  var d = _.find(memo, function(e) { return e.date === el.date });
  if (d) {
    d.Post += el.Post;
    d.Pickup += el.Pickup;
  } else {
    memo.push(el);
  }
  return memo;
}, []);

var array = [  
  {date: '2016-09-10', 'Post': 5, 'Pickup': 2},  
  {date: '2016-09-11', 'Post': 8, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 0, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 3, 'Pickup': 0},  
  {date: '2016-09-13', 'Post': 1, 'Pickup': 2},  
  {date: '2016-09-13', 'Post': 1, 'Pickup': 0} 
];

var result = _.reduce(array, function (memo, el) {
  var d = _.find(memo, function(e) { return e.date === el.date });
  if (d) {
    d.Post += el.Post;
    d.Pickup += el.Pickup;
  } else {
    memo.push(el);
  }
  return memo;
}, []);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Comments