将一个数组值与另一个数组值进行比较
Comparing one array value with another array
我有一个数组,它的值是:
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 =预览
相关文章:
- JavaScript数组包含一个值
- 使用事件更改数组的一个元素
- 从 javascript 数组创建一个 Jquery 数组
- 使用javascript匹配字符串中数组的一个元素
- Angular2从数组创建一个列表
- 在Javascript数组或一个对象中存储多个数据所需的Tweak
- 你能给被劫持的JavaScript数组添加一个函数吗
- 从带有循环的数组中一个接一个地在画布上绘制形状
- 将图像数组从一个窗口传递到另一个窗口,并在javascript的新窗口中显示图像
- 使用拆分字符串的数组创建一个对象
- 多维数组 - 创建一个表
- 将数组从一个函数传递到另一个函数
- 如何将复选框值的数组从一个JSP页面传递到另一个页面
- 使用Knockout.Js将数组绑定到表,并将数组的一个项绑定到另一个元素
- 需要访问数组从一个js到另一个
- 我如何发送数据像数组从一个html文件到另一个html页面
- 从另一个对象和要保存的键数组生成一个对象的最简洁的方法
- 用另一个js数组填充一个javascript数组
- 将对象数组从一个函数传递到另一个函数
- 根据另一个值数组过滤一个对象数组,返回一个空列表