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

Comparing one array value with another array

本文关键字:数组 另一个 比较 一个      更新时间:2023-09-26

我有一个数组,它的值是:

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数组并快速检查新对象中是否存在具有相同键的用户。

通过删除嵌套循环,下面的代码在线性时间内运行,而不是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;
};

try this

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

if语句

var j = 0;

 userDetails.push(userID[j]);

您应该尝试使用$filter。

JS:

var userIds = ["55f6c3639e3cdc00273b57a5", 
        "55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];
$scope.userList = [
    {id: "55f6c3639e3cdc00273b57a5", name: "ASD"},
    {id: "55f6c36e9e3cdc00273b57a6", name: "XYZ"}
  ];
$scope.filteredList = $filter('filter')( $scope.userList, function(user){
  return userIds.indexOf(user.id) != -1;
});

http://plnkr.co/edit/J6n45yuxw4OTdiQOsi2F?p =预览