简体   繁体   中英

Sort two array value and merge as per date using Angular.js/JavaScript

I have two json array and both the array has date field value. Here I need to compare both the array and merge into one array. My code is below:

var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08'}];

var secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09'}];

Here I have two array and I need to compare both the array as per date and merge the both value into one single array. The expected output is given below.

var finalArr=[{'name':'Ram','date':'2017-12-06','model':'mmm'},{'name':'Raja','date':'2017-12-07','model':''},{'name':'Rahul','date':'2017-12-08','model':''},{'name':'','date':'2017-12-09','model':'rrr'}]

My expected output is given above. I was trying like below.

angular.forEach(firstArr,function(obj1){
            angular.forEach(secondArr.task,function(obj2){
                if (new Date(obj1.date)=== new Date(obj2.date)) {

                }
            })
        })

But like this I am little bit confused about the two array length because it may/may not same.

I'm focusing on JS part and not on angular version.

Logic

  • Since you need to merge object based on a date string, you can create a hashMap with dateString as property and object as value.
  • Then you can use Onject.assign to merge objects. If you cannot, you can even use for..in loop or just have 2 loops and set specific property manually.
  • Now loop over this hashMap and retrieve grouped objects.

Sample:

 var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08'}]; var secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09'}]; var hashMap = {}; [firstArr, secondArr].forEach(function(arr) { arr.forEach(function(obj) { hashMap[obj.date] = Object.assign(Object.create(null), hashMap[obj.date] || {}, obj); }) }); var result = Object.keys(hashMap).map(x=> hashMap[x]); console.log(result) 

You can use array#reduce to get the merged object with the same date. Inside the array#reduce , merge objects with the same date and then get all the values using Object.values() .

 var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08'}], secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09'}]; var result = firstArr.concat(secondArr).reduce((r, o) => { r[o.date] = Object.assign({}, r[o.date] || {name:'', model: ''}, o); return r; },{}); var output = Object.values(result); console.log(output); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

try this

var finelArr = []
 angular.forEach(firstArr, function(val) {
     angular.forEach(secondArr, function(item) {
         if (val.date === item.date) {
             finelArr.push({ name: val.name, date: val.date, model: item.model })
         }
     })
 })

Try this. If you do not want to modify the original arrays, you will have to deep clone them beforehand. In contrast to Edison's solution, this will also include items from the second array.

 var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08'}]; var secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09'}]; const newArr = (arr1, arr2) => { const finalArr = arr1.map((firstElement) => { firstElement.model = ""; arr2.forEach((secondElement, index) => { if (secondElement.date === firstElement.date) { firstElement.model = secondElement.model; arr2.splice(index, 1); } }); return firstElement; }); arr2.forEach((element) => { element.name = ""; finalArr.push(element); }); return finalArr; }; console.log(newArr(firstArr, secondArr)); 

Angular is huge framework with big library , but only thing it need before start using correct syntax in view.

This sample worked without coding in controller:

 var app = angular.module("app", []); app.controller("ctrlA", function($scope) { var firstArr = [{ 'name': 'Ram', 'date': '2017-12-06' }, { 'name': 'Raja', 'date': '2017-12-07' }, { 'name': 'Rahul', 'date': '2017-12-08' }]; var secondArr = [{ 'model': 'mmm', 'date': '2017-12-06' }, { 'model': 'rrr', 'date': '2017-12-09' }]; $scope.ul = firstArr.concat(secondArr); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrlA"> <ul> <li ng-repeat="li in ul | orderBy:'date'"> {{li.name ? li.name : li.model}} - {{li.date}} </li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM