Leveraging JavaScript to compare two arrays and generate a novel array of objects that excludes any items with matching id values

I have a task at hand where I need to create a new array in JavaScript that does not contain objects matching by their id field, using two arrays of objects.

The first array consists of:

[{id: 1, name: "Jo"}, {id: 2, name: "Pat"}, {id: 3, name: "Mike"}]

And the second array contains:

[{id: 1, name: "Jo"}, {id: 2, name: "Pat"}, {id: 3, name: "Mike"}, {id: 4, name: "Mitch"}, {id: 5, name: "Karl"}]

The expected result should be:

[{id: 4, name: "Mitch"}, {id: 5, name: "Karl"}]

I am aiming to achieve this using lodash for better efficiency. It's worth noting that the first array will always be smaller or equal to the second array and will only contain objects present in the second array.

My attempt so far is as follows...

let newArray = _.reject(secondArray, {'id': firstArray});

Despite trying this solution, I haven't been successful yet and require assistance with the correct syntax.

Thank you in advance for your time and support.

Answer №1

Concise and to the point. (Assuming one contains the first array and two contains the second array)

const oneIDs = one.map((a) => a.id);

const result = two.filter((a) => !oneIDs.includes(a.id));

Explanation:

First, create an array of all the id's from elements in the first array.

Then, filter out all elements from the second array whose id's are not present in the lookup array (oneIDs).

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

What steps can be taken to stop the page from refreshing and losing its state when cancelling navigation using the back and forward browser buttons in React-router v4.3?

I'm currently facing an issue with a page in which user inputs are saved using a react context object. The problem arises when a user navigates away from the page without saving their entries. I want to prompt the user to either continue or cancel, wh ...

How to retrieve an image from an external source using jQuery

There's a link that looks like this: http://vignette4.wikia.nocookie.net/2007scape/images/c/c1/3rd_age_amulet.png/revision/latest?cb=20141217224859 and I'm trying to figure out how to download it into a specific folder with a specific name usin ...

Simpler and more sustainable methods for embedding HTML elements using a configuration file

Currently, I am devoting my time to a toy project that heavily relies on JavaScript. A key component of this project is a JSON file that contains configurations and input descriptions, along with range values and options. This JSON file enables me to easil ...

Utilizing AJAX with jQuery in Laravel 5

I am currently utilizing Laravel 5 for my project and I am implementing filters on some collections in my controller. The challenge I am facing is integrating AJAX as the intermediary between the blade template and Controller. Below is the jQuery code I am ...

Error encountered: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...

React Native bug: For Loop displaying only the initial element in the Array

I'm currently working on a function that is meant to iterate through 20 elements of an array called smn to display the elements that meet a specific condition. However, with my current code, I am only able to display the first element in the array: ...

Reading and extracting information from an HTML page using jQuery

My goal is to extract a specific value from an AJAX response that is in HTML format. Below is the AJAX call I am working with: var result = $.ajax({ //datatype : "application/json", type: "POST", url: ddcUrl ...

Is it possible to caution users before refreshing the page, while still allowing them to

I have a script that displays a warning message to the user when they attempt to refresh the page. It works perfectly for that purpose. However, my issue is that this same alert pops up when a user clicks on a button or a link within the website itself. I ...

Ancient queries carry the weight of time

Extremely ancient, very old, incredibly aged beyond belief ...

Retrieve the index of the currently selected item in the dropdown menu

Here is my current select setup: <select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select> I am trying to retrieve the index value of the sele ...

Error encountered while attempting to parse JSON data: cannot convert Array to String implicitly

Currently working with Rails 4.2.3 and attempting to parse JSON data using the following code: content = ["{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData& ...

Sending data to a modal within a loop

I am looking to modify the functionality of my current table setup. Currently, the table is generated by iterating through all the samples passed to it via the context in views.py of my Django app, and this setup is working well. However, I want to imple ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

Having trouble pinpointing the source of a Bad Request error in Discord.js (Node) and struggling to understand its

I am currently working on coding a bot in Discord.js (Node) and facing an issue while trying to send an embed with the server information. Despite having all the necessary code, I keep encountering a Bad Request error. Here is the snippet of the problemati ...

What is the best way to change a string into JSON format using JavaScript?

For a recent web project, I utilized the Django framework in conjunction with a MongoDB database. In this project, I implemented a feature where a set of data objects from the database are assigned to a combobox. Interestingly, I incorporated two comboboxe ...

Use jQuery UI draggable to create a clone with a shadow effect

Attempting to replicate this: This is what I have for the draggable element: $( function() { $('#sidebar .question-constructor').draggable({ connectToSortable:'#preview', scroll: false, helper : 'clone ...

Having trouble compiling my project with Typescript, Jest, @types/jest, and ts-jest

I'm currently utilizing jest for mocking my axios requests. Here is an example of my test implementation: // External imports import axios, { AxiosPromise } from 'axios' // Personal imports import { getProgramApplications } from '#sto ...

Is there a way to showcase the image input outcomes directly on the current page?

Looking for a way to showcase the image input results from a card game that I have developed. About the game: Game mechanics: There are 4 categories, each with 9 cards. Players need to choose one card from each category. Initially, all cards are selected ...

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...

Accessing data from a PHP function in JavaScript

Struggling with retrieving an array from a PHP function in a separate file and passing it to JavaScript. I attempted using the code below but nothing seems to be happening. Here is the PHP code: $sprd_array; $spread = 0; foreach ($data as $key => ...