登录
首页 >  文章 >  前端

JavaScript数组对象:如何合并属性值相同的元素?

时间:2025-02-20 09:34:00 394浏览 收藏

最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《JavaScript数组对象:如何合并属性值相同的元素?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

JavaScript数组对象:如何合并属性值相同的元素?

JavaScript数组对象:合并相同属性值的元素

本文介绍如何高效合并JavaScript数组中属性值相同的元素。 我们将使用reduce函数实现这一目标。

以下代码演示了如何将数组中groupId属性值相同的元素合并:

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);

代码逻辑:

  1. 使用reduce函数迭代数组arr
  2. previous数组存储合并后的结果。
  3. current表示当前迭代的元素。
  4. last表示previous数组的最后一个元素。
  5. 如果current.groupId为-1,则直接添加到previous
  6. 如果last存在且last.groupIdcurrent.groupId相同,则将current添加到last.group数组中。
  7. 否则,创建一个新对象,包含groupId和一个group数组(包含current),添加到previous

最终,resArr将包含合并后的数组。 此方法高效地处理了属性值相同的元素合并,并对groupId为-1的元素进行了特殊处理。

本篇关于《JavaScript数组对象:如何合并属性值相同的元素?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>