Analyzing two arrays of objects and identifying the variance in Javascript

I am working with two arrays of objects:

\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]

My goal is to find the available offers, which are only the offers that have not been reserved yet.

\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]

Here is a solution I found on Stack Overflow related to getting the difference between two arrays of objects in JavaScript

Even after trying various solutions from the provided link, I have not been successful. The result I get is always the sum of all objects from both arrays.

function comparer(otherArray){
    return function(current){
        var reserveDay = new Date(current.Day)
           return otherArray.filter(function(other){
               var offerDay = new Date(other.Day)
                   return other.DeskUID == current.DeskUID && offerDay == reserveDay
                       }).length == 0;
                           }
                               }

var onlyInA = offers.filter(comparer(reservations));
var onlyInB = reservations.filter(comparer(offers));

result = onlyInA.concat(onlyInB);

Answer №1

If you want to condense everything into a single function, you can do so like this:

const available = offers.filter(offer => { 
  return reservations.findIndex(reservation => reservation.DeskUID === offer.DeskUID && sameDateTime(new Date(reservation.Day), new Date(offer.Day))) === -1;
});

function sameDateTime(d1, d2) {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
}

console.log(available);

Here's what's happening in the code snippet...

  • offers.filter iterates through each element in the offers array.
  • reservations.findIndex checks if there is a matching reservation for the current offer by comparing unique IDs and dates.
  • If the result is -1, it means no reservation exists, marking the offer as available.

I used string dates for simplicity, but you can easily adjust them to Date objects. Hope this solution proves useful!

UPDATE

To facilitate date comparison, I included a helper function that compares if two dates are from the same day. For more details, refer to: how to tell if two dates are in the same day?

Answer №2

To filter the reservations, you can use a Set and apply the necessary filters.

var getUniqueKey = ({ DeskUID, Day }) => [DeskUID, Day].join('|'),
    availableOffers = [{ DeskUID: "B11A13", Day: "2020-06-06" }, { DeskUID: "B11A13", Day: "2020-06-07" }, { DeskUID: "B12B34", Day: "2020-06-23" }],
    reservedDesks = [{ DeskUID: "B11A13", Day: "2020-06-06", Name: "Mike" }, { DeskUID: "B12B34", Day: "2020-06-23", Name: "Ali" }],
    reservedSet = new Set(reservedDesks.map(getUniqueKey)),
    openOffers = availableOffers.filter(o => !reservedSet.has(getUniqueKey(o)));

console.log(openOffers);

Answer №3

To successfully filter the data, you need to include the some function inside it.

var offers = [{ DeskUID: "B11A13", Day: "2020-06-06" }, { DeskUID: "B11A13", Day: "2020-06-07" }, { DeskUID: "B12B34", Day: "2020-06-23" }];
var reservations = [{ DeskUID: "B11A13", Day: "2020-06-06", Name: "Mike" }, { DeskUID: "B12B34", Day: "2020-06-23", Name: "Ali" }];

var result = offers.filter(k=>!reservations.some(d=>d.DeskUID == k.DeskUID && d.Day==k.Day));

console.log(result);

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

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

Tips for updating the border color of a div upon clicking it

Currently working on a project using react/typescript and facing an issue with changing the border color and width of a div upon clicking it: <div className="showroom-card " onClick={() => setSelection({ showroom: &ap ...

Analyzing two arrays to identify distinct values

I'm stuck on a simple problem and need some fresh ideas: var previousValues : Array = [ 4, 5, 6 ]; var currentValues : Array = [ 3, 4, 6, 7 ]; I aim to extract the values from currentValues that do not appear in previousValues - 3, 7 I aim to extr ...

Creating a dynamic 2D array inside a function by utilizing pointers to retrieve the address of the allocated object

Could someone please provide guidance on how to pass pointers to dynamically allocated arrays using function arguments? Specifically, I am trying to write a function that allocates a 10x10 array (skipping checks for simplicity). Is this approach feasible ...

Can you explain how to convert a List of objects into Json format and then display it in a <tbody> using C#?

I'm struggling to find an example of how to convert a List<object> to Json format and then populate a <tbody> in C#. Can anyone help? List result = new List (); MyClass m1 = new MyClass(); MyClass m2 = new MyClass(); result.Add(m1); res ...

What is preventing the function from successfully compiling text from various files that are uploaded using the HTML5 file reader into an array?

My current challenge involves attempting to upload two text files using the HTML 5 file reader. While I can successfully get the files into an array, encountering difficulty arises when trying to return that array from the function. One solution could be ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...

Facebook's open graph feature allows users to share their own content

Can the original content be customized for each user who shares their page from my website, showing their description and picture? I attempted to use the following code for the title: <meta property="og:title" content="<?php echo ['postTitle&ap ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

Is it possible for a Three.js raycaster to detect an intersection with a group of

I am trying to determine if my raycaster is looking at a loaded OBJ. The OBJ seems to be a THREE.Group with 3 children, not a THREE.Object as expected from Cinema4D exports. Can I modify the raycaster code to target this group instead of an object? raycas ...

Preventing Internet Explorer from automatically scrolling to the top of the page when a new HTML element is dynamically inserted using

On my webpage, I have an ASP:Grid with a small copy button in each row to copy the text inside that cell. The javascript function I created for copying the text is as follows: var copyText = function (textToCopy) { $(".copy").append("<textarea id=&ap ...

Apply a new class to all Radio buttons that were previously selected, as well as the currently

Struggling with a simple code here, trying to figure out how to add color (class) to the selected radio button and the previous ones. For example, if button No3 is selected, buttons 1, 2, and 3 should get a new color. Below is the basic code snippet: < ...

I must incorporate an intermediate Array within the loop

I have a question about using an intermediate array within a loop. Here is the code in question: NSMutableArray *interArray = [[NSMutableArray alloc] initWithCapacity:2]; NSMutableArray *finalyArray = [[NSMutableArray alloc] init]; NSInteger a; for(int j= ...

What is the best way to create a matrix using jagged arrays in Java?

Here is the code snippet I am working with: public class matrixExample { public static void main(String[] args) { int m[][] = new int[5][5]; int count = 1; for (int i=0; i<m.length; i++) for(int j=0; j< ...

Hide the search popup when the user clicks on the "find" button within the jqgrid

What is the solution to closing the search popup when clicking on the Find button? When I search for data in jqgrid and click on the Find button, the Search popup remains open even though the data has been filtered. How can I close the popup after searchin ...

Processing JSON data from a Kafka stream in Spark using the UpdateStateByKey function

Currently, I am parsing JSON data from Kafka within Spark. The data includes start and end tags to indicate the beginning and conclusion of a transaction. Here is an example of the JSON data: ` { "accountId": 1, "name": "start"}, { "accountId": 1 ...

Refresh the page to verify if the user has successfully established a connection with PhoneGap through AngularJS

I am currently developing an app using PhoneGap. I have successfully implemented a feature to check if the user is connected to the internet or not. However, if the user is not connected, I would like to provide a button for them to click on in order to re ...

Using AJAX and JavaScript to enhance a form before submitting it

As a PHP developer delving deeper into AJAX, I have encountered a perplexing issue that I need help resolving. I am dynamically generating a form like so: function addSearchResult(label, tz) { var html = ''; html += '<div>&ap ...