Home > front end >  How to compare 2 elements inside 2 arrays? I would use the below its only for when comparing to a si
How to compare 2 elements inside 2 arrays? I would use the below its only for when comparing to a si

Time:04-04

This is not quite the function for it. How can you Loop thru each array to compare values? Or should these data structures be different? Or transformed first?

Here's the data being compared. Goal is to compare userID with DocumentID.

const videos = 
  [ { userID: '5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2', name: 'Wedge Antilles',  faction: 'Rebels' } 
  , { userID: '8',                            name: 'Ciena Ree',       faction: 'Empire' } 
  , { userID: '40',                           name: 'userIDen 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(videos, index) { 
  return videos["userID"] === blocked.documentID 
})

console.log(result)

CodePudding user response:

Well, you have different ways to do this. For example, you can use javascript functions map and includes in the following way:

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

But you know that this will execute the operation in time O(nxm) (where n is the size of the first array and m is the size of the second one).

CodePudding user response:

I would transform these blocked into an object/map, and then try to filter through it.

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

// then
var result = videos.filter((videos) => bMap[videos.userID])
  • Related