Determine if two arrays have the same object values

I have a situation where I am working with two arrays of objects.

arr1 = [{ name: "John" }, { name: "Frank" }];

arr2 = [
  { name: "John", age: 35 },
  { name: "Frank", age: 22 },
  { name: "Kate", age: 23 },
  { name: "Donald", age: 18 },
];

My task is to compare these arrays. If the key/value pair name matches between the two arrays, I need to add the key/value pair selected: true to the object in the second array.

Answer №1

If you want to efficiently store and compare the names in two arrays, you can utilize the Set method for array manipulation. By creating a set from the first array's names and then mapping over the second array, you can easily identify the common names as shown below:

const arr1 = [{ name: "John" }, { name: "Frank" }];

const arr2 = [
  { name: "John", age: 35 },
  { name: "Frank", age: 22 },
  { name: "Kate", age: 23 },
  { name: "Donald", age: 18 },
];

const arr1Set = new Set(arr1.map(o => o.name));
const result = arr2.map(o => arr1Set.has(o.name) ? { ...o, selected: true }: o);
console.log(result);

Answer №2

If you want to check for matching items between two arrays, utilize the map method to iterate through each item in the second array (arr2). Then, use the .some function to verify if an item with the same name exists in the first array (arr1). In your return statement, consider using a ternary syntax: if the element is "isSelected", return a merged object created using the spread operator ...; otherwise, return the original unaltered object.

const arr1 = [{ name: "Mary" }, { name: "Bob" }];
const arr2 = [
  { name: "Mary", age: 30 },
  { name: "Bob", age: 40 },
  { name: "Alice", age: 25 },
  { name: "David", age: 35 },
];

const result = arr2.map(obj2 => {
  const isSelected = arr1.some(({name}) => name === obj2.name);
  return isSelected ? {...obj2, selected: true} : obj2;
});

console.log(result);

Answer №3

To transform the structure of arr2, you can utilize the map function to verify the presence of an item from arr1.

Solution

const arr1 = [{ name: 'Alice' }, { name: 'Bob' }];

const arr2 = [
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 25 },
    { name: 'Eve', age: 21 },
];

const result = arr2.map((obj) => {
    return arr1.find(({ name }) => name === obj.name)
        ? { ...obj, match: true }
        : obj;
});
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

Exploring the capabilities of SwiftUI to create custom nested array structures using For

Recently, I've encountered a challenge with a nested array of a particular model: let models = [[ButtonModel]] struct ButtonModel: Identifiable { let id = UUID() let value: String let style: ColorStyle init ...

React-native horizontal sliding plugin

Can anyone recommend a reliable horizontal slider plugin for react-native? I've come across some options, but they haven't been working as smoothly as I'd hoped. ...

Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible w ...

I could really use some assistance with this project for my friend

Whenever I click on the image, it only displays two out of the three possible alerts. How can I make it show all three? Here's my code: <!DOCTYPE html> <html> <head> </head> <body> <img src="http://www.build ...

How to efficiently modify a nested array element in MongoDB

I need to update the mobile number for a guardian in the system. Here is an example of the document structure: { "_id" : ObjectId("575e4d850d61a206084ff035"), "students" : [ { "_id": "58454c8fd01c35cb06ac1d7c", ...

Strategies for aligning tooltips with the locations of dragged elements

One of my projects involves a simple drag element example inspired by Angular documentation. The example features a button that can be dragged around within a container and comes with a tooltip. <div class="example-boundary"> <div ...

I am currently attempting to generate a chart that displays information on countries utilizing the restcountries API. Despite being a beginner in this area, I have encountered some challenges and am seeking guidance

I'm struggling to display detailed information for each country separately. Whenever I try to loop through the data, all the contents end up getting merged into a single cell. What can I do to achieve the desired result? https://i.stack.imgur.com/dZS ...

Is it advisable to modify the value of props by using toRef in the Composition API?

I've noticed a common practice in the CompositionAPI where props are converted to refs using `toRefs` function. This has left me feeling a bit confused. For instance, citing the Vue 3 official guide: export default { props: { user: { type ...

What is the best way to eliminate blank values ("") from an array?

I am working with a two-dimensional array that was generated from an HTML table using jQuery, but I have noticed that some values are empty and are displaying as "". How can I go about removing these empty values from the array? <table> ...

Video texture incorporated into Three.js

I'm currently experimenting with using a specific section of a video as a texture on a Three.js mesh. The video in question can be found at this link: . It features a fisheye lens, and I am only interested in incorporating the central circular portio ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

How can you ensure seamless synchronization while logging in a user with ReactJS and retrieving data from the API?

Is there a way to synchronize and run these two functions in succession before calling console.log(user) and setLogin()? The goal is to ensure that all the information retrieved from the API is available in the user context before activating the setLogin() ...

When utilizing AJAX within a for loop, the array position may not return the correct values, even though the closure effectively binds the scope of the current value position

Is this question a duplicate of [AJAX call in for loop won't return values to correct array positions? I am following the solution by Plynx. The issue I'm facing is that the closure fails to iterate through all elements in the loop, although the ...

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

The problem encountered with the Enzyme mount API is a TypeError where it is unable to read the property 'find' of an undefined variable

After converting my component to a stateless one, I started encountering an error that says: TypeError: Cannot read property 'find' of undefined Previously, my tests were running smoothly before the switch. As far as I know, you can test functio ...

Troubleshooting: Issues with jQuery.on method functionality

I'm currently using jQuery version 1.9.1 and I have a situation where I need to perform an action on a dynamically added td element. I attempted to utilize the jQuery.on function, however my code is not being triggered. Can someone please provide some ...

Transmit information to the server

Currently, I am in the process of creating an iPhone app. My goal is to utilize JavaScript to send longitude and latitude values retrieved from the phone to a server for the purpose of initiating a search function. Should I familiarize myself with cross-do ...

What is the most effective method for handling extremely large Long numbers in Ajax?

When it comes to Javascript, all numbers are represented as double-precision floating-point. This can result in a loss of precision when handling numbers that exceed the 64 bit Java Long datatype limit of 17 digits. For instance, a number like: 7143412520 ...

Changing a property of an object in Angular using a dynamic variable

It seems like I may be overlooking a crucial aspect of Angular rendering and assignment. I was under the impression that when a variable is updated within a controller's scope, any related areas would automatically be re-evaluated. However, this doesn ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...