reduce方法实现对数组相邻相同元素进行合并

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45416217/article/details/109800489