compare two different sets of data and exclude the duplicate elements

var arr1 = [11, 12, 13];
var arr2 = [
      { id: 11, name: "name 1" },
      { id: 12, name: "name 2" },
      { id: 13, name: "name 3" },
      { id: 14, name: "name 4" },
];

These two arrays are given and I need to filter the second array to only include items with IDs matching those in the first array, like so:

  var newArray = [
          { id: 11, name: "name 1" },
          { id: 12, name: "name 2" },
          { id: 13, name: "name 3" },
    ];

What is the most optimal way to achieve this?

Answer №1

To start, create an index by linking each unique identifier to its respective object. The structure of the index object should resemble this:

{
  '11': { id: 11, name: 'name 1' },
  '12': { id: 12, name: 'name 2' },
  '13': { id: 13, name: 'name 3' },
  '14': { id: 14, name: 'name 4' }
}

There are various methods to construct this index, one option being using Object.fromEntries. Employ

Object.fromEntries(arr2.map(obj => [obj.id, obj]))
.

Next, associate each id from your arr1 with its corresponding object through a lookup in the established index object: index[id]. This process can be achieved with arr1.map(id => index[id]).

var arr1 = [11, 12, 13];
var arr2 = [
      { id: 11, name: "name 1" },
      { id: 12, name: "name 2" },
      { id: 13, name: "name 3" },
      { id: 14, name: "name 4" },
];

const index = Object.fromEntries(arr2.map(obj => [obj.id, obj]));
const result = arr1.map(id => index[id]);
console.log(result);

This strategy excels in efficiency as it avoids conducting a linear search for every item's index (rendering no need for .includes or .find per entry). Instead, it capitalizes on the swift hashtable retrieval of a property within an object (maintaining more or less constant time complexity). Overall, the operation is O(N) rather than O(N^2).

Nonetheless, be cautious as there may be elevated overheads when generating such an index with small N values. Yet, for larger N values, this method will prove superior and particularly useful if there are multiple variations of arr1 objects to be paired with a single arr2.

Answer №2

Here's a straightforward filter that accesses the element with the id and verifies if that specific id is present in the initial array.

var primaryArr = [11, 12, 13];
var secondaryArr = [
      { id: 11, name: "name 1" },
      { id: 12, name: "name 2" },
      { id: 13, name: "name 3" },
      { id: 14, name: "name 4" },
];
var filteredArray = secondaryArr.filter(item => primaryArr.includes(item.id));

console.log(filteredArray);

Update: For efficiency purposes, here is another tactic:

var primaryArr = [11, 12, 13];
var secondaryArr = [
      { id: 11, name: "name 1" },
      { id: 12, name: "name 2" },
      { id: 13, name: "name 3" },
      { id: 14, name: "name 4" },
];
var objIds = primaryArr.reduce((obj, item) => (obj[item] = true) && obj, {})
var newFilteredArray = secondaryArr.filter(item => objIds[item.id]);

console.log(objIds, newFilteredArray)

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

Delaying the search in Jquery until the input is finalized

Is there a way to delay the search trigger until the user finishes typing? I'm utilizing a function created with mark.js () which initiates the search as the user types, resulting in jumping to the first result during the search. However, the issue is ...

Shut down a Bootstrap modal 5 seconds following the asynchronous submission of a form using Vue.js

As a beginner in JavaScript and Vue, I am currently working on hiding a modal after submitting a form using Bootstrap 5, Vue 2, and Django 3.2. While I can successfully submit the form asynchronously with fetch and clear the fields, I am struggling to clos ...

Switching a cookie from JavaScript to AngularJS: A step-by-step guide

Getting a cookie in AngularJS can be done in a more standardized way. Instead of the traditional JavaScript approach, you can implement it using AngularJS code as shown below: angular.module('myApp', []) .factory('CookieService', func ...

Working with both Javascript and jQuery code within a single HTML file

I recently created a website and on one of the pages, I added some jQuery elements like a start button and progress bar. However, when I tried to implement a JavaScript timer on the same page by adding the script into the header, the jQuery elements stoppe ...

Retrieve text excluding a specific class or id using jQuery

I need help with extracting text from an HTML div. <div id="example"> I am writing a <span class='outer'>query for help <span class='inner'>on a coding forum</span></span> </div> const te ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

Which regular expression should be used to validate names with international characters?

Currently in my PHP project using Codeigniter, I am implementing form validation. Specifically, I have configured the validation rules for the name field like this: $this->form_validation->set_rules('name', 'Nombre', 'requir ...

Methods for transferring checkbox values from JavaScript/view to controller in MVC

Currently, I am developing a form that allows users to select up to 11 football players from a list using checkboxes. The players are categorized and named by their playing positions. @if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x ...

What is the best way to merge multiple window.onscroll events together?

One feature is a colorful RGB scroller positioned next to the standard scrollbar, indicating the progress of page scroll. The second feature is a classic "scroll to top" button. FIRST FEATURE HTML <button onclick="topFunction()" id="myB ...

Checking for null values using the "and/or" syntax

While reading an article on special events in jQuery, I came across a syntax that was unfamiliar to me: var threshold = data && data.threshold || 1 I have previously encountered the following: var threshold = data.threshold || 1 As far as I kno ...

Is there a way to create a scroll down and scroll up button that is located outside of the scroll box

A game designer challenged me to create a custom scrollbar with unique up and down button styles, as well as a custom-looking scrollbar. I wanted to achieve this without using the native browser scrollbar on Windows in Google Chrome. https://i.sstatic.net ...

Using JSON formatting with NVD3 charts

Is there a method to transform my JSON data into a format that NVD3 will accept for a multi bar chart? I have a template set up in NVD3 here: http://jsfiddle.net/hohenheim/6R7mu/5/ The JSON data I want to display is as follows: [{"date": 1396828800, "imp ...

PHP code to retrieve the value of a parent-child relationship

I have a list of elements as shown below array ( 0 => array ( 'id' => '1', 'job_id' => 'J1', 'parent_id' => '0', ), 1 => array ( 'id' => & ...

Automatically submitting the form before proceeding to the following page of the form

I recently received a multi-page form that was designed for me. Each page of the form includes a submit button to save data to a database, a previous button to go back one page, and a next button to move forward. Unfortunately, I've noticed that the d ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

How can I showcase a timestamp data type element that I fetched from Firestore?

Currently, I am looking to showcase the data stored in my Firestore collection. One crucial element in this collection is the "date" field, which is categorized as timestamp. However, upon attempting to display these values, an error message surfaces: E ...

Is your WordPress one-page scroll JQuery script failing to function properly?

Currently attempting to develop a single page scroll feature. Within WordPress, my navigation contains anchor tags structured as follows: <a href="#contact">Contact</a> <a href="#about">About</a> The corresponding divs for the li ...

A bizarre quirk involving dates in JavaScript

Here is the code snippet: function format_date( date, index ) { if ( !date || ( index && !( date[ index ] ) ) ) { return ''; } console.log( date ); var date = new Date( ( index === undefined ) ? date ...

Utilize the `npm ls somepackage` command to adhere to version range specifications

I need to utilize npm ls to pinpoint the source of security warnings. Reference to the documentation states that: Positional arguments consist of name@version-range identifiers, which will restrict the outcomes to only the paths leading to the specified ...

Backbone.js struggles with rendering collection object fields when the JSON response is enclosed within a "book" domain wrapper

Upon receiving the following JSON data, the view and HTML code successfully renders the values on the webpage. JSON DATA [{"id":"1234","name":"book1","type":"catg1"},{"id":"1235","name":"book2","type":"catg1"}, {"id":"1236","name":"book3","type": ...