reduce方法实现对数组相邻相同元素进行合并
发布日期:2021-05-20 10:06:55 浏览次数:27 分类:技术文章

本文共 999 字,大约阅读时间需要 3 分钟。

1、 业务需求

渲染一个表格数据,对相同元素进行合并单元格。

在这里插入图片描述

2、这里我们需要判断数组前一个元素是否和后一个元素相同,如果相同就进行合并,并且给出重复出现的数值。

  • 实现代码
  • 这里主要用到了reduce方法,下面代码是对数组进行处理,不同的数组结构处理方法不同, 这里只分享我的业务代码仅供参考。
  • 关于reduce用法可自行百度。
function getNewCourseList(list) {
list.map(item => {
item.courseList.map(courseListItem => {
courseListItem.count = 0; return courseListItem; }) return item; }) const newList = []; list.forEach(function (item) {
let newArray = [item.courseList[0]]; item.courseList.reduce(function (accumulator, currentItem) {
if (accumulator.stuSectionCourseOutputList[0].realCourseName === currentItem.stuSectionCourseOutputList[0].realCourseName) {
newArray[newArray.length - 1].count += 1; } else {
newArray.push(currentItem); } return newArray[newArray.length - 1]; }) newList.push({
classSection: item.classSection, courseList: newArray }) return newArray; }); return newList; }

在这里插入图片描述

转载地址:https://blog.csdn.net/weixin_45416217/article/details/109800489 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:ant-design树选择框生成treeData数据结构
下一篇:react中函数带()和不带()引发的问题

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月15日 00时48分30秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章