如何判断数组对象的重复数据并统计重复次数?
给定一个数组对象,其中包含多个数据项,每个数据项都有一个唯一的字段"NO"。需要根据"NO"字段判断是否存在重复数据,并为每个数据项添加一个新的字段"重复次数"来显示重复的次数。
以下是一个代码示例,演示如何实现这一功能:
const 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 result = list.reduce((s, v) => { const index = s.findIndex((it) => it.NO === v.NO); if (index !== -1) { s[index] = { ...v, startTime: s[index].startTime, endTime: getNowDate(), count: ++s[index].count }; } else { s.push({ ...v, count: 1, startTime: getNowDate(), endTime: getNowDate() }); } return s; }, []); console.log(result);
此代码对数组对象进行了循环,使用reduce方法将重复的数据项合并并更新count字段的值。
以上就是如何判断数组对象中的重复数据并统计重复次数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号