数组根据某个字段 获取重复项 数组某个字段先累加再去重
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 1.获取重复项 不重复项<br><br>const List=[ { name: '大学女友' , age:20, type: '正宫' }, { name: '隔壁姐姐' , age:24, type: '微信' }, { name: '楼上阿姨' , age:32, type: '阿姨' }, { name: '小区妹妹' , age:18, type: '微信' }, ] let key = {} //存储的 key 是type的值,value是在indeces中对应数组的下标 let indices = [] //数组中每一个值是一个数组,数组中的每一个元素是原数组中相同type的下标 List.map((item, index) => { //根据对应字段 分类(type) let type= item.type let _index = key[type] if (_index !== undefined) { indices[_index].push(index) } else { key[type] = indices.length indices.push([index]) } }) // 归类结果 let result = [] indices.map((item) => { item.map((index) => { //result.push(List[index]) 相同项排序在一起 //if (item.length > 1) {} 只要重复项 //if (item.length == 1){} 只要单独项 //我这里需要重复项 根据业务处理 if (item.length > 1) { result.push(List[index]) } }) }) //结果 //[{ name:'隔壁姐姐',age:24,type:'微信'}, {name:'小区妹妹',age:18,type:'微信'}] |
2.累加去重
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | const arr = [ {id:1,typeId:1,num:2}, {id:2,typeId:1,num:5}, {id:3,typeId:2,num:2}, {id:4,typeId:2,num:1}, {id:5,typeId:3,num:2}, {id:6,typeId:3,num:2}, {id:7,typeId:3,num:2}, ]; let newArr=Object.values(arr.reduce((res,v)=>{ if (res[v.typeId]) res[v.typeId].num += v.num; else res[v.typeId] = v; return res; }, {})) console.log(newArr) //----结果 {id:1,typeId:1,num:7}, {id:3,typeId:2,num:3}, {id:5,typeId:3,num:6}, |
转载于: https://blog.csdn.net/m0_49256439/article/details/126246914
转载于: https://segmentfault.com/q/1010000039780071?utm_source=sf-hot-question
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现