<script>
let chushiArr = [{
gradeName: '2021级',
stageName: '小学'
},
{
gradeName: '2022级',
stageName: '小学'
},
{
gradeName: '2026级',
stageName: '小学'
},
{
gradeName: '2029级',
stageName: '小学'
},
{
gradeName: '2023级',
stageName: '小学'
},
{
gradeName: '2020级',
stageName: '小学'
},
{
gradeName: '2023级',
stageName: '初中'
},
{
gradeName: '2023级',
stageName: '初中'
},
{
gradeName: '2020级',
stageName: '初中'
},
{
gradeName: '2029级',
stageName: '初中'
},
{
gradeName: '2020级',
stageName: '高中'
},
{
gradeName: '2019级',
stageName: '高中'
},
]
// 找到没有重复的阶段
function getunion(arr) {
if (arr && arr.length > 0) {
let newList = [];
for (let i = 0; i < arr.length; i++) {
if (newList.indexOf(arr[i].stageName) == -1) {
newList.push(arr[i].stageName)
}
}
return newList;
}
};
let nainjiArr = getunion(chushiArr);
console.log("阶段", nainjiArr)
//根据gradeName字段进行升序排列
function compare(property, desc) {
return function (a, b) {
var value1 = a[property];
var value2 = b[property];
if (desc == true) {
// 升序排列
return parseInt(value1) - parseInt(value2);
} else {
// 降序排列
return parseInt(value2) - parseInt(value1);
}
}
}
let arr = chushiArr.sort(compare("gradeName", true));
// 构造数据结构
function changeList(sateArr, changeArr) {
let doUseArr = [];
if (sateArr && sateArr.length > 0) {
for (let i = 0; i < sateArr.length; i++) {
doUseArr.push({
stageName: sateArr[i],
cont: [],
})
for (let k = 0; k < changeArr.length; k++) {
if (sateArr[i] == changeArr[k].stageName) {
doUseArr[i].cont.push({
gradeName: changeArr[k].gradeName
})
}
}
}
}
return doUseArr;
};
console.log("最后的排序", changeList(nainjiArr, arr));
</script>
我们发现数字加汉字也是进行直接排序的哈;
通过 return parseInt(value1) - parseInt(value2) 进行排列