0
var arr1 = [{
    "name": { "s1": 2 },
    "type": { "t1": 2 },
    "info": { "m1": 2 },
    "date": "2017-06-04"
  },
  {
    "name": { "s1": 3 },
    "type": { "t1": 3 },
    "info": { "m1": 3 },
    "date": "2017-06-05"
  }
];

var arr2 = [{
  "name": { "s1": 1 },
  "type": { "t1": 0 },
  "info": { "m1": 2 },
  "date": "2017-06-05"
}];

I have two array need result as below:

[
  {
    "name": { "s1": 2 },
    "type": { "t1": 2 },
    "info": { "m1": 2 },
    "date": "2017-06-04"
  },
  {
    "name": { "s1": 4 },
    "type": { "t1": 3 },
    "info": { "m1": 5 },
    "date": "2017-06-05"
  }
]
0

1 Answer 1

4

Using lodash, concat the arrays, groupBy date, and merge the objects. While merge, if both values are numbers, return their sum.

var arr1 = [{"name":{"s1":2},"type":{"t1":2},"info":{"m1":2},"date":"2017-06-04"}, {"name":{"s1":3},"type":{"t1":3},"info":{"m1":3},"date":"2017-06-05"}];

var arr2 = [{"name":{"s1":1},"type":{"t1":0},"info":{"m1":2},"date":"2017-06-05"}];

var result = _(arr1)
  .concat(arr2)
  .groupBy('date')
  .map(function(group) {
    return _.mergeWith({}, ...group, function(o1, o2) {
      if(_.isNumber(o1) && _.isNumber(o1)) {
        return o1 + o2;
      }
    });
  })
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.