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