Looking to compare two elements within different arrays? The method outlined below is specifically designed for comparing to individual values rather than entire arrays

Is this the right approach? How can we iterate through each array to compare values? Should these data structures be modified or transformed first?

Below is the data that needs to be compared. The objective is to match userID with DocumentID.

const videos = 
  [ { userID: '5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2', name: 'Wedge Antilles',  faction: 'Rebels' } 
  , { userID: '8',                            name: 'Ciena Ree',       faction: 'Empire' } 
  , { userID: '40',                           name: 'Iden Versio',     faction: 'Empire' } 
  , { userID: '66',                           name: 'Thane Kyrell',    faction: 'Rebels' } 
  ] 
 
const blocked = 
  [ { id:  2, name: 'Wedge Antilles', documentID: '5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2' } 
  , { id:  8, name: 'Ciena Ree',      documentID: 'Empire'                       } 
  , { id: 40, name: 'Iden Versio',    documentID: 'Empire'                       } 
  , { id: 66, name: 'Thane Kyrell',   documentID: 'Rebels'                       } 
  ] 
var result = videos.filter(function(video) { 
  return blocked.some(blockedItem => video.userID === blockedItem.documentID)
})

console.log(result)

Answer №1

There are various approaches you can take to achieve this task. One method involves utilizing javascript functions such as map and includes. Here is an example implementation:

var blockedIds = blocked.map(function(blockedItem, index) {
  return blockedItem.documentID;
});
var result = videos
  .filter(function(videos, index) {
    return blockedIds.includes(videos["userID"]);
  });

It's important to note that this approach has a time complexity of O(nxm) (where n represents the size of the first array and m denotes the size of the second array).

Answer №2

To improve efficiency, I suggest converting the blocked items into an object or map format and then using that to filter through.

const blockedMap = Object.fromEntries(Object.values(blocked).map(item => [item.documentID, item]))

// apply filtering
var filteredVideos = videos.filter((video) => blockedMap[video.userID])

Answer №3

To achieve this, follow the steps below:

  • Retrieve the documentID by using the Array.map() method in a separate array, only comparing documentID with the userID.
  • Utilize the Array.filter() method to compare the videos array with the documentIDArray and filter out the matching results.

Example :

const videos = [{
  userID: '5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2',
  name: 'Wedge Antilles',
  faction: 'Rebels'
}, {
  userID: '8',
  name: 'Ciena Ree',
  faction: 'Empire'
}, {
  userID: '40',
  name: 'Iden Versio',
  faction: 'Empire'
}, {
  userID: '66',
  name: 'Thane Kyrell',
  faction: 'Rebels'
}]; 

const blocked = [{
  id: 2,
  name: 'Wedge Antilles',
  documentID: '5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2'
}, {
  id: 8,
  name: 'Ciena Ree',
  documentID: 'Empire'
}, {
  id: 40,
  name: 'Iden Versio',
  documentID: 'Empire'
}, {
  id: 66,
  name: 'Thane Kyrell',
  documentID: 'Rebels'
}];

// Retrieve documentID using Array.map() method in a separate array for comparison.
const documentIDArray = blocked.map((obj) => obj.documentID);

// Use Array.filter() method to compare videos array with documentIDArray to filter out matched results.
var result = videos.filter(video => documentIDArray.includes(video['userID']));

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

Initial Year Setting for MUI X datepicker

For a project I am working on with my client, they have requested that the datepicker in MUI X default to the year 2023. They would like the datepicker to automatically display the year 2023 with the option for them to change it if needed, as most of the d ...

What is the best way to send an array and file in the same AJAX request?

When attempting to send both an image file and an array through my AJAX request to a PHP script, I encountered an issue where either the array or the image file doesn't appear. The problem seems to stem from the specific lines that need to be added to ...

Use the `string.replace()` method to swap out strings in a nested object with values from a separate file

Is there a way to swap out the placeholders __fruit_type__, __clothing_type__, __fitness_equipment__, __meditation_app__ in collection.js with the corresponding values from values.js? I'm attempting to do this using the string.replace() Method co ...

What is the reason for the inability to input a null byte in a file when using ascii mode with node.js?

Below is the code snippet I have written: var fs = require('fs'); var fp = fs.openSync('binary.txt', "w"); var byte = '\0'; fs.writeSync(fp, byte, null, 'ascii'); However, upon execution, when I check the con ...

The sticky header is malfunctioning due to a null offsetTop value

import React , {useRef, useEffect} from 'react' import './header.css' const nav_links =[ { path:'#home', display:'Home' }, { path:'#about', display:'About& ...

PHP and MySQL form is not being updated with new data

In my database, the fields include: id,name,email_id,address,phone_no,username,password,category,date <?php include_once('connect_to_mysql.php'); if(isset($_POST["submit"])){ $a=mysql_real_escape_string($_POST["name"]); ...

Determine whether the click occurs inside or outside of a bar on a ChartJS graph

I'm currently working with a bar graph using chartJS. I'm trying to figure out how to detect where the user clicked - whether it was inside or outside of the bar region in chartJS. const waterFChart = new Chart(canvasRef.current, { plugins: [ ...

Obtain the leaf nodes from a combination of arrays and objects using Lodash

Here is the code structure I want to share with you before explaining my requirements. It displays the input array layout along with the desired outcome: [ { link: "someurl", name: "Foo", subCats: [ { link: "anotherurl", ...

Verify changes in the Cross Domain RSS feed by utilizing Ajax technology

I have a website where I am trying to automatically reload an RSS news feed from every 60 seconds if it has been updated. I attempted to use Ajax for this purpose, but I seem to be facing some issues: <script type="text/javascript" src="../js/jquery.a ...

Error message: "No elements were found in Ember.js jQuery cycle slideshow"

As I transition a traditional HTML site to an Ember.js application, I encountered a problem with the jQuery Cycle slideshow plugin. With approximately 10 slideshows on the site, I aimed to create a reusable partial to pass data to. Although the data passi ...

When does an xmlHttpRequest object parse serialized XML into a DOM during its lifecycle?

When a JavaScript code with xmlHttpRequest.responseXML() runs, it creates a DOM Document object from the XML-structured HTTP response body. Have you ever wondered at what moment the XML string is turned into the DOM Document by an xmlHttpRequest object? ...

I am experiencing an issue where the tooltip does not appear when I click the icon. What adjustments can be made to the code to ensure that the tooltip

I have created a feature to copy abbreviation definitions when the clipboard icon is clicked. A tooltip displaying 'Copied' should appear after clicking the icon, but for some reason, it's not visible. Here's the code: $(document).re ...

Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume. My goal is to have two active input fields (one for mass and one ...

What is the best way to implement transition effects while toggling between light mode and dark in tailwind 2.0?

Currently, I am working on a small project utilizing tailwindCSS and have decided to incorporate a dark mode feature. To achieve this, I created a button that toggles the dark class in the html tag. However, upon testing the functionality, I noticed that t ...

The issue of the marker vanishing upon refreshing the page on AngularJS

Currently, I am encountering a rather peculiar issue. Upon the initial page load, the code snippet below correctly displays a marker at the specified coordinates and ensures the map is properly centered: <div class="paddingtop"> <map data-ng- ...

What should I do to resolve the message 'Ignoring invalid configuration option passed to Connection' that I received?

This is the latest message: Warning - Invalid configuration option passed to Connection: createDatabaseTable. Currently a warning, future versions of MySQL2 will throw an error for passing invalid options. The application stops responding after enco ...

Triggering a pop-up window to appear without user interaction on the specified date within the function

I am looking to automatically trigger a pop-up window when my website loads after a specific date that I define within a function. How can I set up the date function for this task? I want the pop-up window to appear automatically on 27/07/2011, and every ...

Submitting data twice through AJAX POST requests

Using a PHP file called via AJAX to insert data into MySQL. Prior to the insert statement, the PHP code runs a select query to check for duplicate records and then proceeds with the insert statement. Problem: When calling the PHP file from AJAX, it gets ...

What is the best way to activate a Rails controller action in response to a JavaScript event?

I'm in the process of developing a Rails application and I have a requirement to trigger an Update action from one of my controllers based on a JavaScript event. Here's what my controller action looks like currently: def update @subscrip ...

Leveraging AngularJS html5mode in conjunction with express.js

Client-side: when("/page/:id", { templateUrl: "partials/note-tpl.html", controller : "AppPageController" }); $locationProvider.html5Mode( true ); Html: <a ng-href="/page/{{Page._id}}">{{Page.name}}</a> Server-side: app.use("/pag ...