我需要排序的对象数组包括所有的孩子,通过比较标题和以前的孩子的属性。
初始数据:样本输入
预期结果:示例输出
const original = []; // get data from json.
const sorted = sortNav(original)
const sortNav = items => {
let result = [...items].sort(function (a, b) {
if(a.title === b.previous || a.previous === null) {
console.log("comparing ...", a.pathTitle, " > ", b.pathTitle)
return -1;
}
if (a.previous === b.title || b.previous === null) {
console.log("compare ...", a.pathTitle, " < ", b.pathTitle)
return 1;
}
return 0;
})
console.log("sorted =>", result);
for(let i = 0; i < items.length; i++) {
if (items[i].children && items[i].children.length) {
console.log("calling sort for children of ", result[i].title, result[i].children)
items[i].children = sortNav(items[i].children);
}
}
return result;
};
它对一些内心的孩子不起作用,我不明白我错过了什么。
我认为您需要定义一个排序函数,并像这样递归地传递它
var origArray = ['a','b','c',['a','b','c']];
function SortRecursive(a, b){
let aArray = Array.isArray(a);
let bArray = Array.isArray(b);
if(aArray == bArray){
if(aArray){
a.sort(SortRecursive);
b.sort(SortRecursive);
return a[0] > b[0] ? -1 : a[0] < b[0] ? 1 : 0;
} else {
return a > b ? -1 : a < b ? 1 : 0;
}
} else {
return aArray && !bArray ? -1 : !aArray && bArray ? 1 : 0;
}
}
origArray.sort(SortRecursive);
这可能并不完全是你想要如何排序你的数据,因为我们没有得到你的数据是什么的例子,但你应该能够看到我做了什么与子数组。
作为一个方面,不,这也将对同一数组进行多次排序,因此应该想出一种方法来识别已经排序过的子数组。