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)
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).
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])
You can simply achieve it via below steps :
documentID using Array.map() method in a separate array as we are going to compare only documentID with the userID.Array.filter() method, we can compare the videos array with the documentIDArray to filtered out the matched results.Demo :
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'
}];
// Fetch documentID using Array.map() method in a seperate array as we are going to compare only documentID with the userID.
const documentIDArray = blocked.map((obj) => obj.documentID);
// Now using Array.filter() method, we can compare the videos array with the documentIDArray to filtered out the matched results.
var result = videos.filter(video => documentIDArray.includes(video['userID']));
console.log(result);