如何比较2个数组中的2个元素?我只会在与单个值进行比较时使用下面的值



这不是它的函数。如何遍历每个数组来比较值?还是这些数据结构应该有所不同?还是先转型?

这是正在比较的数据。目标是比较userIDDocumentID

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)

好吧,有不同的方法可以做到这一点。例如,可以通过以下方式使用javascript函数mapincludes

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

但您知道,这将在时间O(nxm(执行操作(其中n是第一个数组的大小,m是第二个数组的尺寸(。

我会将这些块转换为对象/映射,然后尝试通过它进行过滤。

const bMap = Object.fromEntries(Object.values(blocked).map(item => [item.documentID, item]))
// then
var result = videos.filter((videos) => bMap[videos.userID])

您只需通过以下步骤即可实现:

  • separate数组中使用Array.map()方法获取documentID,因为我们将只比较documentID和userID
  • 现在使用Array.filter()方法,我们可以将视频阵列与documentIDArray进行比较,以过滤出匹配的结果

演示:

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);

最新更新