What is the best way to compare two object arrays in javascript/angularjs?

Need to merge two objects into one object array by comparing with JavaScript/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"},
    ]

Comparison process involves checking for same date, then comparing start times. If B's start_time exceeds A's start_time, it will be labeled as "late". Similarly, if B's finish_time is lower than A's, it will be marked as "too early".

Answer №1

This seems like a JavaScript problem rather than an AngularJS one in my opinion.

Here is a possible solution:

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]);
}

Check out this link for more details!

Answer №2

Hey there, this is my take on the situation and I believe the code speaks for itself :)

var 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"}
    ];

var 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"}
     ];

function getResult()
{
    var results = [];
    for(var i = 0; i < A.length; i++)
    {
        var objA = A[i];

        for(var j = 0; j < B.length; j++)
        {
            var objB = B[j];

            if(objB.date === objA.date)
            {
                var o = {};
                o.date = objA.date;

                //if start_time of A is less than start_time of B
                if(Date.parse(objA.start_time) < Date.parse(objB.start_time))
                    o.start_time = "late";
                else
                    o.start_time = "on time";

                //if end_time of A is less than end_time of B
                if(Date.parse(objA.finish_time) < Date.parse(objB.finish_time))
                    o.finish_time = "too early";
                else
                    o.finish_time = "on time";

                results.push(o);
            }
        }
    }

    if(results.length !== 0)
        return results;
    
    return null;
}

P.S. The output will consist of objects where the date of A matches the date of B.

Answer №3

It seems like you're looking to compare values in array B with those in A, and determine if the start times are early, late, or on-time.

The solution provided by Joseph Serido will work effectively but might take O(n^2) time. Utilizing JavaScript's ability to access objects by key names, transforming A and B into objects can optimize your code by running only one loop.

var A_Times = {}; //Create an Object
//Using date as Key
A_Times["2013-07-31"] = {start_time:"2013-07-31 17:30:00+10", finish_time:"2013-07-31 20:30:00+10"};
A_Times["2013-08-03"] = {start_time:"2013-08-03 17:00:00+10", finish_time:"2013-08-03 20:00:00+10"};

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

var A_Days = Object.keys(A_Times); //Retrieve all days in A

for(var i=0; i<A_Days.length; i++){
    var day = A_Days[i];
    console.log(day); //Display the Key here
    var A_Data = A_Times[day];
    var B_Data = B_Times[day];
    console.log(A_Data);
    console.log(B_Data);
    //Determine punctuality based on A_Data and B_Data
}

However, if your scenario involves data for just a few days, the added complexity may not be necessary. It's up to you to weigh the trade-offs. Hope this helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript appendChild method not functioning properly with dynamically created image elements in JavaScript code

I recently encountered an issue while working on a website project. I was trying to create an img element using JavaScript, but ran into a problem when I tried to add the src attribute and then use the appendChild function. I'm unsure if I am missing ...

Tips for generating an about:blank webpage featuring a personalized iframe

I'm attempting to create a form with the following functionality: Enter a URL into a text box. Click a button and it opens an about:blank page in a new tab. The opened page contains an iframe that occupies the entire screen, with the src attribute se ...

The HTML Canvas seems to be malfunctioning for some unknown reason

As a beginner in programming, I am struggling to understand why the code below is not working. The first three lines of the script are necessary for another part of the webpage, but I don't see how that would affect the rest of the code: <!DOCTY ...

Expanding Headers with JavaScript

Looking to add a Stretchy Header Functionality similar to the one shown in this GIF: Currently, on iPhones WebView, my approach involves calling a Scope Function On Scroll (especially focusing on Rubberband Scrolling) and adjusting the Image Height with C ...

"Troubleshooting Issue: Why Props in mapStateToProps Aren't Updating After Running an Action in Redux

Adding some context, I utilize Redux to manage updates in a shopping cart list. Essentially, I retrieve the list, add an item to it, and then update the entire list. However, after executing an action, my cartList does not seem to update. Despite consulti ...

Angular 2 keypress validation: Ensuring data integrity through real-time input verification

I am currently facing an issue with implementing number validation in my Angular2 project. I am struggling to replicate the JavaScript code provided below. Here is the HTML: <input type="text" class="textfield" value="" id="extra7" name="extra7" onkeyp ...

Do not trigger mouseleave events when absolute positioned elements have overlapping layers

I am facing a challenge with a table that includes multiple rows that need to be editable and deletable. To achieve this, I have created a <div> containing buttons that should appear when hovering over the rows. While this setup works well, I am enco ...

React Star Rating Component: Issue with Image Display

To all who contributed their time and effort in responding to my previous question, I offer my sincerest apologies. Initially, I had assumed that assistance wouldn't be forthcoming, so I started working on the issue myself. As a result, I have made si ...

Using Styled Components to Implement Background Images in a React Application

I'm currently attempting to pass a background image using a prop, but I'm encountering an issue where it's indicating that url is undefined. const CardImage = styled.div` height: auto; width: 100%; background-size: c ...

(codesandbox) Is there a way to have both the label 'checkbox' and the first option pre-checked and pre-selected?

When working with ReactJS, I am currently in the process of mapping some data. My goal is to have all the label checkboxes and their initial values checked by default. Additionally, I want to implement a feature where unchecking a checkbox will also unchec ...

Tips for effectively crafting a component capable of managing both a value and an observable for that specific value

I'm actually curious about two things. When is it appropriate to pass an observable of an object into a component versus resolving it with the | async method? If I want to create a versatile reusable component that can handle both scenarios - accept ...

Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement. For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be ...

Is there a way to access a specific tab index in Ionic 3.20 from a child page using a function call?

Imagine having a tabs page with 3 index pages. The first index page is the home page, the second is the products page, and the third is the cart page. When navigating from the home page to the search page, there is a button that you want to click in orde ...

Jquery code malfunctioning following an ajax request

Can someone help me troubleshoot an issue I'm having with this Jquery script? It seems that after making an ajax call and replacing the old content, the "slideToggle()" function is not working properly. Despite this, other functions like adding and re ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Access to JSON.stringify is prohibited

I have an array containing objects in JavaScript that I need to save as a .json file. Prior to saving the objects, I displayed them using console.log. // Client Object {id: "1", color: "#00FF00"} Object {id: "2", color: "#FF7645"} Object {id: "3", color: ...

Refresh an iframe smoothly and without any visual distraction (using JavaScript)

Does anyone have a clever solution to dynamically refresh an iframe without the annoying flickering or flashing that usually occurs when the page reloads? Is it possible to incorporate a smooth blur-out and blur-in animation instead of the unappealing flic ...

Encountering issues with rendering in React JS when utilizing state variables

I've been attempting to display content using the render method in React JS, but for some reason, the onClick code isn't executing. I'm currently enrolled in a course on Udemy that covers this topic. import React, { Component } from 'r ...

Create queries for relays in a dynamic manner

I'm using Relay Modern for my client GraphQL interface and I am curious to know if it is possible to dynamically generate query statements within Relay Modern. For example, can I change the original query structure from: const ComponentQuery = graphq ...

Updating a select menu with AJAX without the need for a <div> tag within the form

Utilizing an ajax call to dynamically update a select menu is a common practice. The ajax call fetches the options from a separate .php file and populates the select menu accordingly. Below is the code snippet for inserting the dynamic content using JavaS ...