Find the disparity between values within an object and an array

Given the object and array of numbers below, how can I identify which number in the array is not represented as an ID in the object? In this case, the missing number is 1453.

[
  {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'},
  {id: 1456, itemName: 'Third Location - 107 West 20th Street, Manhattan - New York'}
]

[60, 1453, 1456]

Answer №1

When dealing with a large amount of data-items and multiple ids, my preferred approach is to create a lookup using a Set by mapping each id in the itemList...

const idLookup = new Set(itemList.map(({ id }) => id));

Utilizing a Set or a Map for direct item lookups proves to be much more efficient than repeatedly iterating through an array using methods like find or includes within a filter task.

Filtering out non-matching item-ids becomes simple with...

const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));

...example snippet...

const itemList = [
  { id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland' },
  { id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York' },
];
const idList = [60, 1453, 1456];

const idLookup = new Set(itemList.map(({ id }) => id));
const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));

console.log({ listOfNonMatchingIds });
.as-console-wrapper { min-height: 100%!important; top: 0; }

Answer №2

If you want to find the IDs in your data that are not present in a given list of IDs, you can achieve this by creating an array of existing data IDs using the .map() method and then utilizing the .filter() and .includes() methods.

const data = [
  {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'},
  {id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'}
]

const ids = [60, 1453, 1456];
const dataIDs = data.map(obj => obj.id);  // [60, 1456]
const notExistingIDs = ids.filter(id => !dataIDs.includes(id));

console.log(notExistingIDs);  // [1453]

This will give you an array containing all the Object IDs from the data that are not present in your reference IDs array.

Answer №3

@Roko's method is spot on and likely more efficient. Here's an alternative strategy I came up with utilizing .reduce() and .some():

const data = [
  { id: 60, itemName: "Main Location - 1100 Superior Road - Cleveland" },
  { id: 1456, itemName: "Third Location - 107,West 20th Street,Manhattan - New York" }
];
const ids = [60, 1453, 1456];

const result = ids.reduce(
  (acc, curr) =>
  data.some(d => d.id === curr) ? acc : [...acc, curr], []
);

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

Dealing with empty values while using json_encode function in PHP with a dynamically created array

After exploring the capabilities of the simple HTML DOM for PHP, I've found that it functions quite effectively. However, I encountered an issue when attempting to store the retrieved values in a PHP array. You can view an example of this situation a ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...

I would like to know the best approach to utilizing a PHP array or JSON response within JavaScript

Let me present my workflow briefly. While I initiate an Ajax call from the index.phtml file, the Ajax response is as follows: Array ( [Data] => Array ( [0] => Array ( [PlayerId] => 20150 ...

The inclusion of Bootstrap 4 in the header seems to be causing issues with mouse events not functioning correctly

Exploring the functionalities of Bootstrap 4 and jQuery has been an interesting journey. I recently worked on creating a Navbar with 4 links, where the 4th link has a submenu that opens upon hover. However, I encountered an issue where this functionality o ...

Is it possible to dynamically populate a dependent select box using Jinja variables?

I am currently using Flask with Jinja2 templates, and I need assistance in creating dependent select boxes. How can I achieve this using Jinja2 or a combination of JavaScript and Jinja2 variables? For example: On the Python side: @app.route('/&apos ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

Guide on redirecting to a specific tab data target in Symfony 5

When a user is on the 3rd tab and clicks on a DELETE button, I want to redirect the user back to the same 3rd tab on the page. **Template:** <nav> <ul class="nav nav-tabs"> <li class="nav-item"> ...

Share your message with BotFramework WebChat by simply clicking on the provided link

A chatbot I created using Microsoft Bot Framework has been integrated into my website through DirectLine: <div id="chatbot_body"></div> <script src="https://unpkg.com/botframework-webchat/botchat.js"></script> <script> ...

Choose either immediate offspring or immediate offspring of immediate offspring

I am struggling to create a CSS Selector that follows DRY principles. The selector needs to target elements within a group but not those within a subgroup of the main group. Elements should only be direct children of the main group or wrapped in an addit ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

Problems with Displaying Content in HTML

Having trouble with displaying the apostrophe within my code: if (type == 'Survivor') { display = isProxy ? (finishedRegistration ? '' : 'Unfinished ') + (name.substr(name.length - 1) == 's' ? name + '&rsqu ...

Check the validity of the schema for an array in a

Hi everyone, I need some help with this JSON code I have. var menu = [{ "name": "Computers", "children": [{ "name": "Notebook", "children": [{ "name": "Apple" }, { "name": "Windows" }] }, { "name": "Tablets", "children": [{ "name": "Apple" }, { "name": ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

Is there a proper way to supply createContext with a default value object that includes functions?

As I was creating my context, I set an initial state and passed the necessary functions for useContext. Although this method is functional, I'm concerned it may present challenges in larger projects. Does anyone have suggestions for a more efficient a ...

Angular Directive - introducing a fresh approach to two-way binding and enable "pass-by-value" functionality

In a previous question, I inquired about the possibility of incorporating an attribute on a directive to allow for values to be passed in various formats, such as: <my-directive att> //Evaluates to true <my-directive att="true"> ...

Exploring the usage of slots in WebComponents without relying on shadow DOM

I am working on developing a WebComponent without utilizing ShadowDOM. So far, everything has been going smoothly. However, I now aim to create a component that wraps other components similar to how it is done in Angular with @ViewChild / @ViewChildren. (I ...

How can I create an HTML link that opens a drop-down menu with form functionality?

Feeling a bit perplexed here as I'm not entirely sure how to label this issue... If you're familiar with the Facebook interface, I'm trying to develop a feature similar to the "DOWNWARD ARROW" icon found next to the "comments" or "status" b ...

Nextjs attempting to access local storage without proper initialization

I'm currently working on a feature where I have a sidebar with two buttons, contact and profile. When a user clicks on either of them, the URL updates to: /?section=clickedItem, allowing the user to save the state and return to that specific page upon ...

What is the best way to verify an email address in Vue.js?

Issue with email validation using regex in Vue.js <div class="input-wrapper"> <div class="email-icon"></div> <input type="email" v-model.trim="$v.email.$model" v-validate="'required'" :class="{ 'is-invalid': v ...

Splitting JavaScript files in the "dist" folder based on their source folders can be achieved in Angular by using G

I’m currently utilizing gulp-angular for my project, but I’m facing a challenge due to my limited experience with node and gulp when it comes to modifying the default scripts task. My goal is to generate an optimized JS file for each folder within my ...