Reputation: 5677
I have an array with values like :
userID: ["55f6c3639e3cdc00273b57a5",
"55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];
$scope.userList : [Object, Object, Object, Object, Object],
where each object has an ID property of which i am comparing.
I want to compare whether the each userID
array value exist in userList array or not.
$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;
};
The problem i am facing is for each userID
in the array, i want to compare it with all the items in userList
object to match.
The above code is not working. Its not comparing each array values with the entire object.
Upvotes: 0
Views: 93
Reputation: 32392
Instead of using 2 nested loops, convert $scope.userList
into an object that has the userID
as the key. Then you can loop through your userID
array and quickly check if a user with the same key exists in your new object.
By removing the nested loops, the code below runs in linear time instead of n^2, which is beneficial if you have large arrays. And if you store $scope.userList
as an object that's keyed by its userId
, then you can save even more time by not having to create the index each time the function is run.
$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;
};
Upvotes: 1
Reputation: 316
You should try using $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=preview
Upvotes: 1
Reputation: 38663
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;
};
Changes in this lines on if statement
var j = 0;
and
userDetails.push(userID[j]);
Upvotes: 1