高效统计前端数组中重复数据:基于reduce方法的解决方案
本文介绍一种高效方法,用于统计后台返回数组中重复数据的次数,并避免因数据分批返回导致的计数错误。 假设后台返回的数据包含重复的NO字段,我们需要在前端对这些数据进行去重并统计每个NO字段出现的次数。
问题:直接计数方法在处理连续数据流时,重复计数容易出错。
解决方案:利用reduce方法,实现精确计数。
示例代码:
立即学习“前端免费学习笔记(深入)”;
let list = [ { DF: 343, Fstep: 0.2, NO: 1004 }, { DF: 344, Fstep: 0.2, NO: 1005 }, { DF: 345, Fstep: 0.2, NO: 1004 }, { DF: 346, Fstep: 0.2, NO: 1004 }, { DF: 347, Fstep: 0.2, NO: 1006 }, { DF: 348, Fstep: 0.2, NO: 1005 }];const countDuplicates = (data) => { return data.reduce((acc, curr) => { const existingItem = acc.find(item => item.NO === curr.NO); if (existingItem) { existingItem.count++; } else { acc.push({ ...curr, count: 1 }); } return acc; }, []);};let newArr = countDuplicates(list);console.log(newArr); // 输出包含count属性的去重数组
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。
如若转载请注明出处:http://www.down96.com/tutorials/621.html