$scope.locations = [
{ name : "One"},
{ name : "Two"},
{ name : "Three"},
{ name : "India"},
{ name : "Japan"},
{ name : "China"}
];
$scope.tempLocations = [
{ name : "One"},
{ name : "Two"},
{ name : "global"},
];
我有两个数组。如果 location
不包含 tempLocations
中的某些名称,我想将它们从 tempLocation
中删除。在这种情况下,我想删除位置全局
我尝试了以下方法,但不起作用。
for(var i=0;i<$scope.tempLocations.length;i++){
var index = $scope.tempLocations.indexOf($scope.locations[i]);
if(index == -1){
console.log($scope.tempLocations[i]);
$scope.tempLocations.splice(i,1);
}
}
最佳答案
我猜你正在找这个
$scope = {}
$scope.locations = [
{ name : "One"},
{ name : "Two"},
{ name : "Three"},
{ name : "India"},
{ name : "Japan"},
{ name : "China"}
];
$scope.tempLocations = [
{ name : "One"},
{ name : "Two"},
{ name : "global"},
];
$scope.tempLocations = $scope.tempLocations.filter(function(x) {
return $scope.locations.some(function(y) {
return x.name == y.name
})
})
document.getElementById("output").innerHTML = JSON.stringify($scope.tempLocations, 0,' ');
console.log($scope);
<pre id="output"></pre>
如果您有许多(100+)位置,请考虑首先将它们转换为“关联数组”,例如:
validLocations = { "One": 1, "Two": 1 ... etc
关于javascript - 比较数组并删除不匹配的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25893250/