要从对象数组中快速删除重复项,可以使用多种方法。以下是几种常见的方法及其基础概念、优势、类型、应用场景以及示例代码。
基础概念:
Set
是一种集合数据结构,它类似于数组,但其成员的值都是唯一的。JSON.stringify
将 JavaScript 对象转换为 JSON 字符串。优势:
应用场景:
示例代码:
const removeDuplicates = (arr) => {
const unique = new Set(arr.map(JSON.stringify));
return Array.from(unique).map(JSON.parse);
};
const array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }
];
console.log(removeDuplicates(array));
// 输出: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
基础概念:
Map
是一种键值对的集合,其中键可以是任意类型。优势:
应用场景:
示例代码:
const removeDuplicates = (arr) => {
const map = new Map();
for (const item of arr) {
const key = JSON.stringify(item);
if (!map.has(key)) {
map.set(key, item);
}
}
return Array.from(map.values());
};
const array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }
];
console.log(removeDuplicates(array));
// 输出: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
基础概念:
优势:
应用场景:
示例代码:
const _ = require('lodash');
const array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }
];
const uniqueArray = _.uniqBy(array, 'id');
console.log(uniqueArray);
// 输出: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
问题:对象属性顺序不一致导致去重失败。 解决方法:
Map
方法,因为它不受属性顺序影响。示例代码:
const removeDuplicates = (arr) => {
const map = new Map();
for (const item of arr) {
const sortedItem = Object.keys(item).sort().reduce((acc, key) => {
acc[key] = item[key];
return acc;
}, {});
const key = JSON.stringify(sortedItem);
if (!map.has(key)) {
map.set(key, item);
}
}
return Array.from(map.values());
};
const array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ name: 'Alice', id: 1 }
];
console.log(removeDuplicates(array));
// 输出: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
通过以上方法,可以有效地从对象数组中删除重复项,并根据具体需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云