What is the process for verifying the existence of a key value pair within one array in comparison to another array?

I have two different sets of data, represented by arrays:

invoices: [
    {id: 90, Client: 'Bob', paid: false, total: 900},
    {id: 91, Client: 'Sarah', paid: false, total: 400}
]

and:

result: [{km: 200, hours: 20, Person: 'Sarah'}]

The invoices array is a response retrieved in JSON format via a GET request and may be larger than the result array. For example, the invoices array includes Bob while he does not appear in the result array.

How can I identify the id of objects whose Client does not match any entry in the Person field of the result array? I attempted to accomplish this using nested for loops without success.

Answer №1

By creating an object with keys representing the Person values found in the result array, we can efficiently filter the values in the invoices array and then use map to extract only the id values of the filtered results:

const invoices =  [
    {id: 90, Client: 'Bob', paid: false, total: 900},
    {id: 91, Client: 'Sarah', paid: false, total: 400}
]

const result =  [{km: 200, hours: 20, Person: 'Sarah'}]

const resindexes = result.reduce((c, o, i) =>
  (c[o.Person] = i, c), {});

ids = invoices.filter(o => resindexes[o.Client] === undefined).map(o => o.id);

console.log(ids);

Answer №2

To apply a filter on the invoices Array, utilize the result Array as the argument and search for any Client in it (refer to MDN for Array.filter). Remember, the callback function used with filter should be a standard function (not an arrow function) so that you can access the result-Array for thisArg.

console.log( `Ids not present in result\n`, 
  [ {id: 90, Client: 'Bob', paid: false, total: 900}, 
    {id: 91, Client: 'Sarah', paid: false, total: 400},
    {id: 92, Client: 'Mia', paid: false, total: 200} ]
  .filter( 
    function(v) { return !this.find(n => n.Person === v.Client); }, 
    [{km: 200, hours: 20, Person: 'Sarah'}] // <= thisArg
   )
   .map(v => v.id) // <= fetch the found id's
   .join()
);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Answer №3

Utilizing Set and flatMap provides a concise and effective solution. Set enables quick member checking in an array. As for flatMap, it allows filtering and mapping simultaneously.

// Data
const invoices = [
  {id: 90, Client: 'Bob', paid: false, total: 900},
  {id: 91, Client: 'Sarah', paid: false, total: 400}
];
const personsArr = [{km: 200, hours: 20, Person: 'Sarah'}];

// Query
const persons = new Set(personsArr.map(r => r.Person));
const result = invoices.flatMap(i => !persons.has(i.Client) ? i.id : []);
console.log(result);

Answer №4

To achieve this, you can create a Map of persons.

An advantage of this approach is that you can easily access person data by their name.

Note that I adjusted the invoices by 1 row to improve the result view.

// Enter data here
const invoices = [
    {id: 90, Client: 'Bob', paid: false, total: 900},
    {id: 91, Client: 'Sarah', paid: false, total: 400},
    {id: 92, Client: 'Joe', paid: false, total: 400}
];
const personsArr = [{km: 200, hours: 20, Person: 'Sarah'}];

// Query
const persons = new Map(
    personsArr.map(r =>{ 
        return [r.Person, r]
    }
  )
);
// Invoices without corresponding results
const orphans = invoices.filter((i)=>!persons.has(i.Client));
// ID of invoices without corresponding results
const orphansId = orphans.map((o)=>o.id)

console.log(orphansId);

Resulting in: [ 90, 92 ]

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

Enhancing User Interactions: A Guide to Sorting and Generating Multiple Text Fields using jQuery UI's Droppable

Scenario: I am looking to allow my users to create a shopping list by dragging products into a sortable and droppable list. Depending on the position of the product on the list and its value, the text fields in the form should be automatically filled. Try ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

Managing single sign-out with SSO using the Msal v2 library in a Node.js and Vue.js environment

The challenge: When using msal v2, logging in to the app via a Microsoft account saves parameters to the sessionStorage. Everything works perfectly until the user logs out on Office.com or any other site using Microsoft SSO. The problem arises because the ...

Problem with communication: Client successfully sends data but does not receive anything using ng-websocket and ws

My client-side WebSocket server in AngularJS is able to successfully send data to the server. However, when trying to send data from the server to the client, the client does not seem to respond to the event. I am using angular-websockets on the client si ...

Robmongo - combine unique values based on different columns

As a newcomer to robmongo, I've been tasked with writing queries for a collection that includes keys like "userId" and "deviceModel." My goal is to create a query that shows the number of users for each device model. Here is the query I have so far: ...

React - Incorrect components experiencing style changes due to setTimeout

Check out the code snippet here: https://jsfiddle.net/69z2wepo/204131/ A main component displays two 'notifications' each with different disappearance timings. class Page extends React.Component { constructor(props) { super(props); t ...

One way to represent the carriage return character ( ) as text in HTML is by using a JavaScript function to create a

I have encountered a situation in which I need to display \r at the end of a string within a JavaScript function, but unfortunately it is not being displayed. <html> <body> <p>Click the button to create a PRE element.</p> < ...

Combining Date and Time in Javascript: A Guide

As a JavaScript beginner, I am struggling with combining date and time pickers. Despite finding similar questions, I have not yet found the solution I need. I have two inputs: one for the datePicker and another for the timePicker. <form> <div clas ...

When using JavaScript with React, setting a value after the onBlur event can result in users having to click

In my React form, I have an input button with an onBlur event that sets the value to a useState property. However, after the onBlur event is triggered, the user has to click the button twice to focus on it properly. It seems like the page needs time to pro ...

Display the number in a formatted manner without displaying any zeros in the decimal part

Can you help me with a decimal number display issue I am having? <nested:text property="product.price" maxlength="5" onclick="javascript:validatePriceValue(this);"/> number displayed as 44 44.00 I want to use J ...

Why can't I capture the text within this particular div using .text?

Trying to extract specific text from a website in Chrome's developer console. For example, here is the code snippet: <div class="someClass">This is some text!</div> Expected it to work with this command, but it returns 'undefined&a ...

Tips for optimizing webpage loading time by registering a client script resource at the bottom of the page

Lately, I've been finding Extender controls on Asp.net quite annoying. Script controls that inject javascript at the top of the web page have me reconsidering if there is a better way to place them at the bottom, similar to using ClientScriptManager.R ...

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

The program will end once the user inputs -1

In this particular array, all integers except the final one are positive. The last integer in the array is (-1). Can you determine the length (size) of the array? int number; int i = 0; cout << "Please input a number: "; cin >> number; array[0 ...

JavaScript for Audio: How to Play Sound

I've been struggling to make this play a sound in Firefox, IE, or Chrome. No matter what I do, it just won't work. <html> <head> <script type="text/javascript"> function playSound() { var audio = document.createElem ...

Unable to stop the default action in IE for certain code

I am facing an issue on my website where the JavaScript I have implemented to prevent page reload is not working in Internet Explorer. The code functions properly in all other browsers, except IE. Here is the JavaScript code snippet that should prevent pa ...

What is the correct method for verifying if a URL has been generated using the createObjectURL function?

In the scenario I'm facing, users are able to set an image either by providing a URL or by using bytes that are converted into a blob object URL. To prevent resource leaks, it is important to free the blob object URLs when they are changed. However, t ...

How can we prevent components from rendering in React when their state or props have not changed?

I encountered a problem in my project where I have a main component that serves as the parent component of my project. Inside this main component, I have defined routes for other components and directly imported some components like a Side Navbar and Login ...

The error message "Cannot add 'str' and 'NoneType' objects together" is commonly encountered in Web2py

Having difficulty with my ajax call. The function passes a variable to my python controller, which then returns the result of a query. I'm using the Web2py framework. The specific error I'm encountering is: 'cannot concatenate 'str&apos ...

Getting a specific column from a multi-dimensional array using PHP's echo function

Currently, I am working on a PHP project involving multidimensional arrays with string values. My goal is to display only the values from a specific column, rather than showing all values from all columns. First, let's initialize the array! $test = ...