如何用JavaScript按属性分离数组的重复项与非重复项?
按指定属性分离数组中的重复项与非重复项
你可以通过先统计属性值出现次数,再用filter筛选的方式实现需求。核心思路是先遍历数组记录每个目标属性值的出现频次,再根据频次把元素分到两个数组中:所有频次大于1的元素归入重复项数组,频次等于1的归入非重复项数组。
示例数组
const customers = [ { id:1, name: "John", address:"123 street"}, { id:2, name: "Alex", address:"456 street"}, { id:3, name: "John", address:"674 street"}, { id:4, name: "Stacy", address:"534 street"}, { id:5, name: "Blair", address:"634 street"} ];
实现代码
下面是封装好的通用函数,支持传入任意数组和指定属性名:
function splitDuplicatesAndUniques(arr, prop) { // 统计每个属性值的出现次数 const countMap = arr.reduce((map, item) => { const value = item[prop]; map[value] = (map[value] || 0) + 1; return map; }, {}); // 根据频次筛选元素 const duplicates = arr.filter(item => countMap[item[prop]] > 1); const uniques = arr.filter(item => countMap[item[prop]] === 1); return { duplicates, uniques }; } // 调用示例 const { duplicates, uniques } = splitDuplicatesAndUniques(customers, 'name'); console.log('重复项数组:', duplicates); console.log('非重复项数组:', uniques);
输出结果
运行后会得到你期望的两个数组:
- 重复项数组:
[ { id:1, name: "John", address:"123 street"}, { id:3, name: "John", address:"674 street"} ]
- 非重复项数组:
[ { id:2, name: "Alex", address:"456 street"}, { id:4, name: "Stacy", address:"534 street"}, { id:5, name: "Blair", address:"634 street"} ]
这个方案只需要遍历数组两次(一次统计、两次筛选),效率较高,且能灵活适配不同属性名,复用性强。
内容的提问来源于stack exchange,提问作者user3294878
相关产品推荐
相关产品推荐

