如何在JavaScript数组中移除重复的对象?
移除对象数组中的重复项
我有如下对象数组(已修正语法错误):
[ {teamName: 'first', playerId: 316}, {teamName: 'first', playerId: 315}, {teamName: 'first', playerId: 316}, {teamName: 'first', playerId: 316}, {teamName: 'second', playerId: 315}, {teamName: 'second', playerId: 318}, {teamName: 'third', playerId: 318}, {teamName: 'third', playerId: 316} ]
需要编写函数移除数组中的重复对象(当teamName和playerId完全相同时视为重复项),输出结果如下:
[ {teamName: 'first', playerId: 315}, {teamName: 'first', playerId: 316}, {teamName: 'second', playerId: 315}, {teamName: 'second', playerId: 318}, {teamName: 'third', playerId: 318}, {teamName: 'third', playerId: 316} ]
解决方案
方法1:利用Set过滤重复项
将每个对象的teamName和playerId拼接成唯一字符串作为标识,通过Set记录已出现的标识,过滤掉重复项:
const removeDuplicates = (arr) => { const seenKeys = new Set(); return arr.filter(item => { const uniqueKey = `${item.teamName}-${item.playerId}`; if (!seenKeys.has(uniqueKey)) { seenKeys.add(uniqueKey); return true; } return false; }); }; // 测试代码 const originalArr = [ {teamName: 'first', playerId: 316}, {teamName: 'first', playerId: 315}, {teamName: 'first', playerId: 316}, {teamName: 'first', playerId: 316}, {teamName: 'second', playerId: 315}, {teamName: 'second', playerId: 318}, {teamName: 'third', playerId: 318}, {teamName: 'third', playerId: 316} ]; console.log(removeDuplicates(originalArr));
方法2:使用reduce构建唯一集合
通过reduce将唯一标识作为键存储对象,最后提取对象值得到去重后的数组:
const removeDuplicates = (arr) => { const uniqueMap = arr.reduce((acc, item) => { const key = `${item.teamName}-${item.playerId}`; if (!acc[key]) acc[key] = item; return acc; }, {}); return Object.values(uniqueMap); }; // 测试代码同上
两种方法的核心逻辑一致:通过teamName与playerId的组合生成唯一标识,确保相同组合的对象仅保留一个。
内容的提问来源于stack exchange,提问作者fadsgas
相关产品推荐
相关产品推荐

