Search code examples
javascriptangularjsobjectjavascript-objectsarrayobject

How to compare two object array using javascript/angularjs?


I have 2 objects and I want to merge it as one object array but I need first to compare using JavaScript or AngularJS.

A = [
     {date: "2013-07-31", start_time:"2013-07-31 17:30:00+10", finish_time:"2013-07-31 20:30:00+10"},
     {date: "2013-08-03", start_time:"2013-08-03 17:00:00+10", finish_time:"2013-08-03 20:00:00+10"},
     {date: "2013-09-03", start_time:"2013-09-03 17:00:00+10", finish_time:"2013-09-03 20:00:00+10"}
    ]

B = [
     {date: "2013-07-31", start_time:"2013-07-31 17:37:49+10", finish_time:"2013-07-31 20:32:04+10"},
     {date: "2013-08-03", start_time:"2013-08-03 16:57:34+10", finish_time:"2013-08-03 20:00:57+10"}
    ]

Expected output
C = [
     {date: "2013-07-31", start_time:"late", finish_time:"on time"},
     {date: "2013-08-03", start_time:"on time", finish_time:"on time"},
    ]

I will compare first if the two object array have the same date then I will compare the start of the same date then if the start_time value on the B exceeds on A start_time then it will change to a string that it is "late". Also for finish_time if the value on B is lower than A then the string would be "too early".


Solution

  • To me, this is really just a JavaScript issue, not really an AngularJS one.

    I think something like this is what you're looking for:

    const A = [
         {date: "2013-07-31", start_time:"2013-07-31 17:30:00+10", finish_time:"2013-07-31 20:30:00+10"},
         {date: "2013-08-03", start_time:"2013-08-03 17:00:00+10", finish_time:"2013-08-03 20:00:00+10"},
         {date: "2013-08-03", start_time:"2013-08-03 17:00:00+10", finish_time:"2013-08-03 20:00:00+10"}
        ];
    
    const B = [
         {date: "2013-07-31", start_time:"2013-07-31 17:37:49+10", finish_time:"2013-07-31 20:32:04+10"},
         {date: "2013-08-03", start_time:"2013-08-03 16:57:34+10", finish_time:"2013-08-03 20:00:57+10"},
         {date: "2013-08-03", start_time:"2013-08-03 16:57:34+10", finish_time:"2013-08-03 19:00:57+10"}
        ];
    
    
    let C = [];
    const maxLength = Math.min(A.length, B.length);
    
    for (let i = 0; i < maxLength; i += 1) {
      const startTimeResult = B[i].start_time > A[i].start_time ? 'late' : 'on time';
      const finishTimeResult = B[i].finish_time > A[i].finish_time ? 'on time' : 'too early';
      C[i] = { date: A[i].date, start_time: startTimeResult, finish_time: finishTimeResult };
      console.log(C[i]);
    }
    

    https://codepen.io/joseph4tw/pen/mXGeoO?editors=1012