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

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

Develop a list of findings from the search

Is there a way to extract the name from the image shown below? return testData.then((data) => { console.log(data) var results = []; var toSearch = params.suggestTerm; data = data["data"]["0"]; console.log(" ...

Is there a way to swap out multiple characters within a string when using ng-repeat in AngularJS?

How can I replace multiple characters in a string using ng-repeat in AngularJS? I've tried the following code, but it's not working. I need to remove #, _, and . from the strings in my list. How can I achieve this in AngularJS? <body> &l ...

Using jQuery to toggle sliding the information above a div

I am facing an issue with my customized sliding menu. The menu slides over the image but not over the content-div, pushing it aside. I have tried to fix this problem but haven't found a solution yet. My goal is for the menu to slide over all divs and ...

ReactJS - Error: Attempting to access the property 'raw' of an undefined variable

I'm currently facing an issue where I am trying to extract specific data from a particular part of an api. Surprisingly, I can view all the data in the console. { "id":"DszAeHV8zfQ", "created_at":"2020-01-28T19:41:06-05:00", "updated_at":"2020 ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Unable to send parameters via URL when making an Ajax request in Rails

Struggling to pass a parameter through a URL in an Ajax request that's triggered by a confirmation dialog. Need the value of that parameter in my Rails controller upon successful request but can't seem to make it work. Tried the following code s ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

Recognizing JavaScript in Intellij IDEA within a script tag that does not specify the type as "text/javascript"

Using the MathJax javascript library has presented a challenge for me. Whenever I make changes to the MathJax configuration, I encounter issues because it is written in javascript but its type is labeled as "text/x-mathjax-config". This causes Intellij Ide ...

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Monitoring $scope modifications within a directive: A simple guide

I am currently working with a directive that looks like this: app.directive('selectedForm', function(MainService) { return { scope: { formName: '=currentForm' }, restrict: 'E', ...

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

What is the best way in jQuery to show each element of an array one at a time with a space in an input field?

I have a large array filled with strings that I want to display one by one in a text field, automatically concatenated with a space bar. Below is my code: <script> x = 0; function abc() { for (i = 0; i < words[x].length; i++) { ...

Vue.js Enhances CoolLightBox with Multiple Galleries

I am trying to set up a page with multiple galleries using CoolLightBox. It worked fine for me when I had just one gallery, but now that I want to create multiple galleries - each with its own image on the page - it is only displaying one image in the ligh ...

The browser is preventing a cross origin request in Fetch

Currently, I am utilizing node, express, and react to build a sign-in portal. In the frontend, I have created app.js and signin.js files. The partial code snippet in the signin.js file looks like this: onSubmitSignIn = () => { fetch("http://localhost:3 ...