gpt4 book ai didi

javascript - 将一个数组值与另一数组进行比较

转载 作者:行者123 更新时间:2023-11-28 19:00:48 25 4
gpt4 key购买 nike

我有一个数组,其值如下:

userID: ["55f6c3639e3cdc00273b57a5", 
"55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];

$scope.userList : [Object, Object, Object, Object, Object],

其中每个对象都有一个我正在比较的 ID 属性。

我想比较每个userID数组值是否存在于userList数组中。

$scope.userInfo = function(userID) {
var userDetails = [];
for (var i = 0; i < $scope.userList.length; i++) {
(function(i) {
for (var j = i; j < userID.length; j++) {
if ($scope.userList[i]._id === userID[j]) {
userDetails.push($scope.userList[i]);
}
}
})(i)
}
return userDetails;
};

我面临的问题是对于数组中的每个userID,我想将其与userList对象中的所有项目进行比较以进行匹配。

上面的代码不起作用。它不会将每个数组值与整个对象进行比较。

最佳答案

不要使用 2 个嵌套循环,而是将 $scope.userList 转换为以 userID 作为键的对象。然后,您可以循环访问 userID 数组并快速检查新对象中是否存在具有相同 key 的用户。

通过删除嵌套循环,下面的代码以线性时间而不是 n^2 运行,如果您有大型数组,这将非常有用。如果您将 $scope.userList 存储为由其 userId 作为键的对象,那么您可以节省更多时间,因为不必在每次调用该函数时都创建索引运行。

$scope.userInfo = function(userID) {

var userList = {};

//create object keyed by user_id
for(var i=0;i<$scope.userList.length;i++) {
userList[$scope.userList._id] = $scope.userList;
}

//now for each item in userID, see if an element exists
//with the same key in userList created above

var userDetails = [];
for(i=0;i<userID.length;i++) {
if(userID[i] in userList) {
userDetails.push(userList[userID[i]]);
}
}

return userDetails;
};

关于javascript - 将一个数组值与另一数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com