Find similarities between two JavaScript arrays using unique identifiers

Seeking a more efficient and streamlined approach in javascript to compare two arrays and generate a third one.

We have the following two arrays :

var array1 = [
    [{
    id: 1,
    enabled: false

  }],
  [{
    id: 2,
    enabled: true,
  }],
  [{
    id: 10,
    enabled: false
  }]
]

var array2 = [
    {
    id_from_array1: 10,
    data: true
  },
  {
    id_from_array1: 20,
    data: false
  },
  {
    id_from_array1: 1,
    data: true
  }
]

The goal is to extract IDs from the second array that are not present in the first array. Currently, this is done by creating a third array with nested loops to compare values of the first two arrays :

var array3 = [];

for (var i = 0; i < array2.length; i++) {
  for (var y = 0; y < array1.length; y++) {
      if (array2[i].id_from_array1 === array1[y][0].id) {
        array3.push(array2[i])
    }
  }
}

Link to working fiddle

Is there a more optimal solution to this problem?

Thank you!

Answer №1

Generate a list of unique id values from array1 and then utilize .filter to extract elements from array2 based on these ids;

var ids = array1.map( el => el[0].id );
ids = Array.from(new Set(ids)); // Extract unique ids using set
var array3 = array2.filter( el => ids.indexOf(el.id_from_array1)!==-1);
console.log(array3);

var array1 = [
    [{
    id: 1,
    enabled: false

  }],
  [{
    id: 2,
    enabled: true,
  }],
  [{
    id: 10,
    enabled: false
  }]
]

var array2 = [
    {
    id_from_array1: 10,
    data: true
  },
  {
    id_from_array1: 20,
    data: false
  },
  {
    id_from_array1: 1,
    data: true
  }
];

var ids = array1.map( el => el[0].id );
var array3 = array2.filter( el => ids.indexOf(el.id_from_array1)!==-1);
console.log(array3);

Answer №2

To locate elements, you can utilize the find method in this way:

let newArray = [];
arrayA.find(function(itemA) {
  let match = arrayB.find(function(itemB) {
    return itemB[0].id === itemA.id_from_arrayA;
  });
  if (match !== null) {
    newArray.push(match);
  }
});

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

The number input component that is meant to be reusable is experiencing functionality issues within the NUXT framework

I have a reusable input component that is being used in various places. Everything works well with the number input, but the issue arises when I completely clear the input. This action triggers a warning message in the console: [Vue warn]: Invalid prop: t ...

How can I programmatically refresh a recursive ng-include in AngularJS?

Using a recursive script within my Angular application, I am displaying a visualization of multiple objects. However, whenever I modify the structure of an object dynamically, the view does not automatically update. It appears that the ng-include directiv ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

Is there a way to navigate to the next or previous image in a lightbox by using ev.target.nextElementSibling or ev.target.prevElementSibling?

I am new to the world of web development Currently, I'm facing an issue with my lightbox feature. I want to navigate between images by using ev.target.nextElementSibling and ev.target.prevElementSibling when clicking on the next/previous arrow.png ic ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

Issue with React ChartJS rendering – Title not visibleWhen using React Chart

I'm currently using react chart js for displaying a doughnut in my component. "chart.js": "^3.7.1", "react-chartjs-2": "^4.1.0", However, I'm facing an issue where the title is not being displayed: const d ...

What is the best way to assign a unique color to each circle?

Struggling to assign random colors to each circle in my canvas. Currently, they all have the same color that changes upon refresh. I'm aiming for unique colors on each circle but my attempts have been unsuccessful so far. Check out my code below: v ...

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

Struggling to send an array through Ajax to Django view?

I am just starting to work with ajax and I want to pass an array from JavaScript to my view. Here is the template. I have a form that takes the course ID number and score from students, creates a table, and adds how many courses the student wants to add. ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

Finding the solution to a variable in a Linq Query using c#

I recently encountered a challenge with a dynamic array that I am working with. Below is the code snippet: dynamic[] queueList = await queueInfo.Run.GetData<dynamic[]>(Name); https://i.sstatic.net/JPlW2.jpg My goal is to extract unique values from ...

What is the best way to use jQuery to fill a dropdown menu with options from a JSON object?

Looking to populate a dropdown box #dropdown with values from a json object stored in a JavaScript string variable. How can I access each element as value/label pairs and insert them into the dropdown? The structure of the json string is as follows: [{"n ...

Issues with implementing Rails 4 with jQuery, javascript, and coffee scripts causing functionality to malfunction

Although I have nearly two decades of experience in C/C++ for control systems and firmware, as well as proficiency in shell and perl scripting, I am new to rails and web development. Despite including jquery in the application.js manifest, I am unable to ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...

Intermittent issue with Webdriver executeScript failing to detect dynamically created elements

It has taken me quite a while to come to terms with this, and I am still facing difficulties. My goal is to access dynamically generated elements on a web page using JavaScript injection through Selenium WebDriver. For instance: String hasclass = js.exec ...

Tips for incorporating external routes into the routes index file

I am currently dealing with a users.js and an index.js file. users.js const express = require('express'); const router = express.Router(); const {catchErrors} = require('../handlers/errorHandlers'); const authController = require(&ap ...

Issues with JavaScript PHP Ajax request

I am currently developing a Single Page Application and facing challenges with Ajax. The two files I am working with are bhart.js and RespSelArt.php. However, my Ajax Call is not functioning as expected. At this point, all I want is to display "worked". H ...

Ways to display jQuery values as HTML text

Trying to concatenate the HTML text with the values of item.certificate_name has been a challenge for me. I've experimented with various methods, but none of them seem to work. The specific line I'm referring to is where I wrote . I have alread ...

loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file: <button mat-raised-button color="primary" mat-button class="nextButton" (click)="calculatePremium()"> Calculate </button> <div id="calcul ...