What is the best method for searching two arrays to determine if there is a match?

I have a list :

[{item:'apple',quantity:5},{item:'banana',quantity:3}]

I also have another list :

[{category:'fruit',id:3435},{category:'vegetable',id:3}]

My goal is to create :

[{newItem:'banana',newId:3}]

I am looking for a solution in JavaScript using the lodash library.

Answer №1

One approach is to create a hash table using the first array and utilize it while iterating through the second array.

const arr1 = [{ name: 'example', id: 1 }, { name: 'sample', id: 3 }],
    arr2 = [{ type: 'example', uid: 3435 }, { type: 'sample', uid: 3 }],
    hashTable = Object.create(null),
    matches = [];

arr1.forEach(function (item) {
    hashTable[item.id] = item;
});

arr2.forEach(function (item) {
    if (hashTable[item.uid]) {
        matches.push({ newname: item.type, uidid: item.uid });
    }
});

console.log(matches);

Answer №2

If you need an array with objects that have different key names, this code snippet could be exactly what you're looking for. It's designed to be easy to understand and doesn't involve any complicated syntax or logic.

var arr1 = [{name: 'blah', id: 1}, {name: 'blah2', id: 3}];
var arr2 = [{type: 'blah', uid: 3435}, {type: 'blah2', uid: 3}];

var arr3 = [];

arr1.forEach(function(obj1, i) {
  arr2.forEach(function(obj2) {
    if (obj1.id == obj2.uid) {
      arr3.push({newname: obj1.name, uidid: obj1.id})
    }
  })
});

console.log(arr3);

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

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 ...

Tips for integrating the C++ icon into a ReactJs project

For a ReactJs project, I needed to include icons of different Languages and Tools. When adding a Python icon, I used: <ListItem> <ListItemIcon className={classes.icon}> <span className="iconify" data-icon= ...

Stopping the spread of popup alerts: A comprehensive guide

I'm having trouble explaining this in English;-) Whenever I select an option, an alert pops up for each choice and I don't know how to stop it. Step 1: Choose the "aaaa" option, for example 1111 alert ... Step 2: Choose the "bbbb" option, for ...

Using React Inline Styles to Set a Background Image

I am facing an issue with accessing a static image to use as a background within the backgroundImage property in React. I have hit a roadblock and need some guidance on how to proceed. My initial thought was that it could be achieved by following these st ...

VueJs - Efficiently displaying elements in a single line using v-for loop for pagination purposes

My current implementation uses a v-for loop to display pagination links: <div v-for="n in this.totalPages"> <router-link :to="'/top/pages/' + n" @click.native="getPaginatedUser">{{ n }}</router-link> </div> However, e ...

Using multiple ng-controller directives with the "controller as x" syntax on a single element

What is the reason that Angular does not allow two ng-controller directives on a single element and What are some potential solutions for this issue - such as using custom directives or nesting HTML elements with a single ng-controller directive, among oth ...

When handling cross-domain Jquery Ajax requests, the error function may unexpectedly return a success status

While attempting a cross domain GET request using jQuery AJAX, I am encountering a situation where the error function returns success as the status. The data I am expecting to be returned from the get service is: document.write("<div class=\"displ ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

Tips for sending parameters to the function in the 'onclick' attribute in reactJS

My goal is to include an 'onclick' event for a checkbox in my code. Here's what I have attempted: <input type='checkbox' name="doneTask" value='done' onClick={removeTask(this)}/> The function 'remov ...

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

What causes the return of 'undefined' during the execution of type coercion?

Can you explain why the type of a variable changes but the value remains undefined when trying to set it? let average; // Do I need to initialize with 'average = 0;' for it to work properly? for (const [oddName, odd] of Object.entries(game.odd ...

Utilize a chrome extension to showcase specific content on designated webpages through the use of

I'm currently working on creating a Chrome extension for Pinterest integration. After referencing some examples from the Chrome extension demo (specifically one that displays an icon in the omnibox when the URL contains a 'g'), I made modif ...

Tips for transferring button ID values to an input field upon clicking?

Is there a way to transfer the ID of a button to a hidden input field? In my scenario, I am using a foreach loop to display users and create delete buttons for each. The goal is to pass the ID of the clicked button to a hidden input located within a modal ...

How to retrieve the value of a SelectField component within a constant using Material-UI

I am currently facing an issue with my Drawer component that contains a SelectField with some fields. I am struggling to get the value and implement the onChange functionality of the Field. Below is the snippet of my code: const DrawerCargoAddItem = (p ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...

Is there a way to transfer JSON data from a JSP page to a Spring REST controller efficiently?

Attempting to send data from a jsp page containing datetime, zoneid, checked checkboxes with values, and unchecked checkboxes with null values. Despite sending all this as json to my spring rest controller, I noticed in debug mode that the controller only ...

Is it possible to customize the icon or color of the filter on a Kendo UI grid?

When I am filtering a kendo grid, I need to change the color of the "watering can" icon that appears above the columns. I have found a way to run my code on the filtering event: var originalFilter = self.object.data("kendoGrid").dataSource.filter; self.o ...

Adjust time according to specified time zone using JavaScript

I am working on a project involving clocks and timezones. The user should be able to choose a timezone from a combobox, and upon selection, the main digital clock should update to display the time for that timezone. I have a text file called 'zone.txt ...

Exploring key value pairs dynamically in JavaScript

I have a JSON object containing HTTP request information: "http": { "method": "POST", "headers": [{ "content-type": "application/json" }, { "Authorization": "KKYZASSHUYTRJ" }], "url": "http://localhost:8888/download/con ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...