In JavaScript, we are comparing two arrays that contain objects. We will then segregate the identical objects into one array and the unique objects into another

Here are sample arrays:

const firstArray = [
  {
    name: "q",
    age: 10,
    size: "M",
  },
  {
    name: "w",
    age: 10,
    size: "S",
  },
  {
    name: "e",
    age: 10,
    size: "M",
  },
];

const secondArray = [
  {
    name: "q",
    age: 10,
    size: "M",
  },
  {
    name: "w",
    age: 10,
    size: "S",
  },
  {
    name: "i",
    age: 10,
    size: "S",
  },
  {
    name: "x",
    age: 10,
    size: "S",
  },
];

The goal is to compare the first array (firstArray) with the second one (secondArray) based on specific properties - in this case, name and size.

If there is a match, the results should be stored in a new array. If not, they should be stored in another array, resulting in two separate arrays at the end.

This is what I have attempted so far:

for (let j = 0; j < secondArray.length; j++) {
  for (let i = 0; i < firstArray.length; i++) {
    const { name: name1, size: size1 } = firstArray[i];
    const { name: name2, size: size2 } = secondArray[j];

    
    if (name1 === name2 && size1 === size2) {
        matchingArr.push(firstArray.splice(i, 1)[0]);
        break;
    } else {
        nonMatchingArr.push(firstArray[i]);
    }
  }
}

Matched items are stored in matchingArr:

[ { name: 'q', age: 10, size: 'M' },   { name: 'w', age: 10, size: 'S' } ]

Non-matching items are stored in nonMatchingArr:

[ { name: 'e', age: 10, size: 'M' },
  { name: 'e', age: 10, size: 'M' } ]

Expected result in nonMatchingArr:

[ { name: 'e', age: 10, size: 'M' } ]

I would appreciate any guidance or assistance on improving this logic.

Answer №1

Your inner loop is struggling to determine whether an element should be added to y because not all values of arr2 have been fully processed yet. Only after considering all the values in arr2 can such an addition take place.

The fact that you do not remove the item from arr once it is included in y explains why it might get pushed multiple times.

Furthermore, using splice within a loop over the same array leads to skipped indexes, potentially resulting in incorrect outcomes.

An effective solution would be to generate a unique identifier for each element in the second array by creating a Set, combining relevant attributes like name and size using a separator that does not exist in the size value. Subsequently, iterate through the first array and verify if the generated key exists in the set or not:

const arr = [{name: "q",age: 10,size: "M",},{name: "w",age: 10,size: "S",},{name: "e",age: 10,size: "M",},];
const arr2 = [{name: "q",age: 10,size: "M",},{name: "w",age: 10,size: "S",},{name: "i",age: 10,size: "S",},{name: "x",age: 10,size: "S",},];

const set = new Set(arr2.map(({name, size}) => size + "/" + name));

const x = [], y = [];
for (let obj of arr) {
    (set.has(obj.size + "/" + obj.name) ? x : y).push(obj);
}

console.log("x:");
console.log(x);
console.log("y:");
console.log(y);

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

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Displaying additional content with the load more button in JQuery

My script below: Main page: jQuery code <script type="text/javascript"> $(document).ready(function(){ $("#loadmorebutton").click(function (){ $('#loadmorebutton').html('<img src="ajax-loader.gif ...

I am currently encountering an issue with a code snippet that is not performing as anticipated and require clarification

import React, {useEffect, useState} from 'react'; export function App(props) { let [state, setState] = useState(2); console.log('outside', state); useEffect(()=>{ document.querySelector('.btn').addEventListener( ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

Lock an array section in Java

Currently, I am in the process of developing a lock-free binary search tree that is based on arrays. To ensure concurrency, I need to figure out how to lock a specific range of the array within my methods. Do you have any suggestions on how I can accomplis ...

Skipping the word counter code

I was attempting to create a code that would search for a specific word within a string and determine its position in the string. If the word is not found within the string, I wanted it to display a message indicating that the word was not found. For insta ...

Sending information to the parent component via props

I am facing an issue where I need to utilize a value generated within a function in the child.js file and then pass it to parent.js in order to filter an array of children based on this value. Child.js const returnDistance = () => { const ...

Utilizing Javascript for logging into Facebook

Feeling frustrated! I've been struggling to implement the Facebook Login pop-up on my website using the Facebook JavaScript API. Despite following tutorials, I can't seem to make the login pop-up appear. Instead, when I go through the login pro ...

Guide on how to design a schema in Mongoose for uploading arrays of objects in MongoDB

[ const arrayOfObjectsSchema = new Schema({ array: [ { title: { type: String, required: true, }, desc: { type: String, required: true, }, img: { type: String, required: tru ...

What is the process behind a BufferedReader's operation for reading characters in an array?

While browsing online, I stumbled upon this piece of code that reads files from a file and converts it into a string. However, one thing is confusing me - how does in.read(arr) read all the contents of a file in one go? import java.util.Scanner; import ...

An issue with struct values returning incorrect results in C arrays

So there's this array of "MyStruct" that I'm working with. typedef struct MyStruct { double a; double b; double c; }MyStruct ; .... MyStruct tab[30]; for (i=0;i<30;i++){ ...

Chrome is blocking the loading of a local image in THREE.js due to cross-origin restrictions

While working with THREE.js, I encountered an issue in the developer console: Cross-origin image load denied by Cross-Origin Resource Sharing policy. This error only occurs when I try to run my script in Chrome. The code snippet in question is as follows ...

The error message "Attempting to send a message using an undefined 'send' property in the welcomeChannel" is displayed

bot.on('guildMemberAdd', (member) => { console.log(member) const welcomeChannel = member.guild.channels.cache.find(channel => channel.name === 'welcome'); //const channelId = '789052445485563935' // welcome c ...

Next JS is successfully importing external scripts, however, it is failing to run them as

In my upcoming project using the latest version 12.1.6, I am incorporating bootstrap for enhanced design elements. The bootstrap CSS and JS files have been included from a CDN in the pages/_app.js file as shown below: import '../styles/globals.css&apo ...

Include a fresh attribute to a current JSON within a FOR loop

My goal is to populate a bootstrap-carousel using a more detailed JSON file pulled from a database. To illustrate, here is an example of my old JSON structure: old.json [ {"screen": [{ "img" : "../static/images/product/34.jpg", "price": "Rs 100", ...

The error message I'm encountering is: "Attempting to use the executeScript method with the argument type (String) is not compatible."

I encountered an issue stating "The method executeScript(String, Object[]) in the type JavascriptExecutor is not applicable for the arguments (String)" and I need assistance to resolve it. driver.findElement(By.id("twotabsearchtextbox")).sendKeys(new St ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

Attempting to dynamically generate a delete button and execute the delete function using JavaScript

On this page, I aim to load the 'skills' from my java application and dynamically generate a Delete button that allows me to remove those 'skills' from the application. An error occurs when trying to click the button to delete a skill. ...

I'm confused as to why I keep receiving alert messages every time I click on a button. Can someone please provide

My aim is to enhance the functionality such that clicking the blue button changes the reading status to either <Yes> or <Not>. Any guidance on this would be greatly appreciated. Additionally, I am puzzled as to why, currently, I receive an aler ...

"Trouble with AngularJS Array Loading: View doesn't show data upon load, but alerts and console

I'm facing an issue where I'm trying to populate an array with values, but it keeps showing up as empty. Oddly enough, the alerts are working correctly. It seems like I might be overlooking something obvious here. Any insights or suggestions on w ...