使用 Lodash 获取两个数组根据 ID 的差集
可以使用 _.differenceBy 函数来实现根据 ID 取两个数组的差集。首先,需要确保两个数组内的对象都有一个唯一的 ID 属性。然后,可以使用 _.differenceBy 函数将两个数组进行比较,并根据 ID 属性的值来取差集。
下面是一个使用 Lodash 实现根据 ID 取两个数组的差集的示例代码:
const _ = require('lodash');
const array1 = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' }];
const array2 = [{ id: 2, name: 'Jane' }, { id: 4, name: 'Alice' }];
const difference = _.differenceBy(array1, array2, 'id');
console.log(difference);
// Output: [{ id: 1, name: 'John' }, { id: 3, name: 'Bob' }]
在上面的示例中,difference 变量将包含两个数组的差集,即在 array1 中存在而在 array2 中不存在的对象。
需要注意的是,_.differenceBy 函数会返回一个新数组,其中包含在第一个数组中出现但未在后续数组中出现的对象。
原文地址: https://www.cveoy.top/t/topic/pgaY 著作权归作者所有。请勿转载和采集!