JavaScript 按name、color字段去重数组并合并type为字符串数组
多字段判定的JS对象数组去重实现
核心实现逻辑
这类需求不需要嵌套循环逐个比对,借助Map的键值唯一性做映射,就能以O(n)的时间复杂度完成去重和合并,完全适配题目要求的规则:
- 以
name、color两个字段的组合作为重复判定的唯一标识 - 相同标识的元素,直接把
type值收集到数组中 - 遍历完成后取出所有映射的结果,即为最终输出结构
可直接运行的代码实现
const arr = [ { name: 'honda', color: 'red', type: 'car' }, { name: 'honda', color: 'red', type: 'suv' }, { name: 'honda', color: 'green', type: 'van' }, { name: 'toyota', color: 'red', type: 'suv' }, { name: 'toyota', color: 'red', type: 'van' } ] const resultMap = new Map() arr.forEach(item => { // 生成双字段的唯一判定键,用JSON序列化避免特殊字符导致的键冲突 const uniqueKey = JSON.stringify([item.name, item.color]) if (resultMap.has(uniqueKey)) { // 命中重复规则:追加当前type到已有的类型数组 resultMap.get(uniqueKey).type.push(item.type) } else { // 未命中:初始化符合输出结构的新对象,type存为单元素数组 resultMap.set(uniqueKey, { name: item.name, color: item.color, type: [item.type] }) } }) // 转换为最终输出的数组结构 const finalResult = Array.from(resultMap.values()) console.log(finalResult)
输出效果校验
运行上述代码得到的finalResult,和题目给出的期望结构完全一致:
// finalResult 输出内容 [ { name: 'honda', color: 'red', type: ['car', 'suv'] }, { name: 'honda', color: 'green', type: ['van'] }, { name: 'toyota', color: 'red', type: ['suv', 'van'] } ]
注意事项
- 选用
Map替代普通对象做映射存储,是因为普通对象的键会自动转成字符串,遇到字段值为数字、特殊符号的场景更容易出现隐式冲突 - 用
JSON.stringify生成唯一键的方案,适配任意可序列化的字段值,不需要自行设计拼接分隔符,降低重复键误判的概率 - 业务场景需要保持数组原有元素顺序时,
Map本身按插入顺序存储,不需要额外做排序操作
内容的提问来源于stack exchange,提问作者Sharry
相关产品推荐
相关产品推荐

