
JavaScript数组对象:合并相同属性值的元素
本文介绍如何高效合并JavaScript数组中属性值相同的元素。 我们将使用reduce函数实现这一目标。
以下代码演示了如何将数组中groupId属性值相同的元素合并:
<code class="javascript">const arr = [
{ title: '标题1', url: 'url', groupId: -1 },
{ title: '标题2', url: 'url', groupId: 123 },
{ title: '标题3', url: 'url', groupId: 123 },
{ title: '标题4', url: 'url', groupId: -1 },
{ title: '标题5', url: 'url', groupId: 456 },
{ title: '标题6', url: 'url', groupId: 456 },
{ title: '标题7', url: 'url', groupId: 789 },
];
const resArr = arr.reduce((previous, current) => {
const last = previous.length ? previous[previous.length - 1] : null;
if (current.groupId === -1) {
previous.push({ title: current.title, url: current.url }); // groupId为-1的元素单独处理
} else if (last && last.groupId === current.groupId) {
last.group.push({ title: current.title, url: current.url }); // 合并到已有组
} else {
previous.push({ groupId: current.groupId, group: [{ title: current.title, url: current.url }] }); // 创建新组
}
return previous;
}, []);
console.log(resArr);</code>代码逻辑:
立即学习“Java免费学习笔记(深入)”;
reduce函数迭代数组arr。previous数组存储合并后的结果。current表示当前迭代的元素。last表示previous数组的最后一个元素。current.groupId为-1,则直接添加到previous。last存在且last.groupId与current.groupId相同,则将current添加到last.group数组中。groupId和一个group数组(包含current),添加到previous。最终,resArr将包含合并后的数组。 此方法高效地处理了属性值相同的元素合并,并对groupId为-1的元素进行了特殊处理。
以上就是JavaScript数组对象:如何合并属性值相同的元素?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号