http://codepen.io/leongaban/pen/GZgrMK?editors=0010
我正在尝试找到最有效的方法来实现这一点,在我的实际应用中,我可能在bigArray中有超过1000个项目,在小数组中可能有几百个项目甚至全部1000个项目。
我需要找到所有这些项目并删除它们。 Lodash比原生javascript API更快,所以这就是我在这里尝试的:
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.greeting = 'The array below should be smaller than bigArray';
$scope.bigArray = [
{ name: 'Leon'},
{ name: 'Eric'},
{ name: 'Wes'},
{ name: 'Gannon'},
{ name: 'Jordan'},
{ name: 'Chris'},
{ name: 'Paulo'},
{ name: 'Gumbo'},
{ name: 'Gilgamesh'}
];
$scope.smallArray = [
{ name: 'Gannon'},
{ name: 'Gumbo'},
{ name: 'Gilgamesh'}
]
$scope.newArray = [];
$scope.removeItems = function() {
_.remove($scope.bigArray, function($scope.smallArray, n) {
return $scope.smallArray[n].name;
});
// $scope.newArray = _.remove($scope.bigArray, function(n) {
// return n.name = _.find($scope.smallArray, 'name');
// });
// _.each($scope.bigArray, function(value, i) {
// _.find($scope.smallArray, 'name');
// });
}
}]);
到目前为止我没有运气的尝试。
证明lodash击败原生Javascript,这些结果来自Mr.zerkms发布的jspref链接: http://jsperf.com/zerkms-forloop-vs-each-from-lodash
答案 0 :(得分:1)
您正在寻找_.filter
而不是_.remove
,我认为
$scope.newArray = _.filter($scope.bigArray, function(item) {
return !_.find($scope.smallArray, {name: item.name});
});
答案 1 :(得分:1)
这只是对@Harangue回答的改进
当第二个数组很大时,它会提高性能
var smallObject = _.keyBy($scope.smallArray, 'name');
$scope.newArray = _.filter($scope.bigArray, function(item) {
return !smallObject[item.name];
});
所以不使用2个循环,我们可以使用1个循环