如何使用 lodash 从 bigArray 中删除 smallArray 中的所有项目?

How to remove all items in smallArray from bigArray with lodash?

http://codepen.io/leongaban/pen/GZgrMK?editors=0010

我正在尝试找到最有效的方法来完成此操作,在我的实际应用程序中,我可能在 bigArray 中有超过 1000 个项目,在 small 数组中有几百个项目甚至所有 1000 个项目。

我需要找到所有这些项目并将它们移除。 Lodash 比原生 javascript APIs 快,所以这就是我在这里尝试的:

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 解决方案?因为 lodash API 在很多方面都比本地 Javascript API.

Proof lodash beats native Javascript,这些结果来自jspref link Mr.zerkms posted: http://jsperf.com/zerkms-forloop-vs-each-from-lodash

你在寻找 _.filter 而不是 _.remove,我认为

$scope.newArray = _.filter($scope.bigArray, function(item) {
   return !_.find($scope.smallArray, {name: item.name});
});

这只是对@Harangue 回答的改进

第二个数组大的时候会提升性能

var smallObject = _.keyBy($scope.smallArray, 'name');
$scope.newArray = _.filter($scope.bigArray, function(item) {
   return !smallObject[item.name];
});

所以我们可以使用 1 个循环而不是使用 2 个循环