JavaScript - 过滤掉两个数组并取出dupes

时间:2017-09-22 22:45:47

标签: javascript arrays lodash

我们说我有两个数组:

var sellersDatabase = [
  { name: 'Mark', start_date: '2017-06-27' },
  { name: 'Jane', start_date: '2017-06-27' }
];

var sellersAPICall = [
  { name: 'Mark', start_date: '2017-06-27' },
  { name: 'Joe', start_date: '2017-06-22' },
  { name: 'Steven', start_date: '2017-04-11' },
  { name: 'Jane', start_date: '2017-06-27' }
];

如何使用ES6或Lodash获得第一个阵列中未包含的那些差异?是的,我已经尝试过lodash' difference()

所以,我的预期输出是:

var toInsertIntoDB = [
  { name: 'Joe', start_date: '2017-06-22' },
  { name: 'Steven', start_date: '2017-04-11' }
];

这样做:

javascript const toInsertToDB = _.difference(sellersDatabase, sellersAPICall); console.log(toInsertToDB);

输出:

[{ "name": "Mark", "start_date": "2017-06-27" }, { "name": "Jane", "start_date": "2017-06-27" }]

(当我想要相反的时候)

1 个答案:

答案 0 :(得分:5)

由于您要比较对象数组而不是基元,请使用_.differenceBy(),并说明应该比较对象的属性。另外,sellersAPICall数组应该是第1个(参考数组)。



var sellersDatabase = [
  { name: 'Mark', start_date: '2017-06-27' },
  { name: 'Jane', start_date: '2017-06-27' }
];

var sellersAPICall = [
  { name: 'Mark', start_date: '2017-06-27' },
  { name: 'Joe', start_date: '2017-06-22' },
  { name: 'Steven', start_date: '2017-04-11' },
  { name: 'Jane', start_date: '2017-06-27' }
];

var result = _.differenceBy(sellersAPICall, sellersDatabase, 'name');

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

如果你想比较2个属性,你可以使用一个连接两个值的回调函数:

&#13;
&#13;
var sellersDatabase = [
  { name: 'Mark', start_date: '2017-06-27' },
  { name: 'Jane', start_date: '2017-06-27' }
];

var sellersAPICall = [
  { name: 'Mark', start_date: '2017-06-27' },
  { name: 'Joe', start_date: '2017-06-22' },
  { name: 'Steven', start_date: '2017-04-11' },
  { name: 'Jane', start_date: '2017-06-27' }
];

var result = _.differenceBy(sellersAPICall, sellersDatabase, function(o) {
  return o.name + '-' + o.start_date;
});

console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;