我正在对一个对象数组进行排序,但在保持空对象的顺序时遇到了问题,下面将按SectionName排序
(() => {
const items = [{
ID: 20,
SectionName: "Cabinet"
},
{
ID: 0,
SectionName: ""
},
{
ID: 0,
SectionName: ""
},
{
ID: 20,
SectionName: "Cabinet"
},
{
ID: 2,
SectionName: "Frame"
},
{
ID: 0,
SectionName: ""
},
{
ID: 3,
SectionName: "Alt"
},
{
ID: 4,
SectionName: "Upper"
},
{
ID: 0,
SectionName: ""
},
{
ID: 0,
SectionName: ""
},
{
ID: 0,
SectionName: ""
},
{
ID: 5,
SectionName: "Lower"
}
];
//items.forEach((e, i) => {
// console.log(e);
//});
// sort by name
items.sort(function(a, b) {
let nameA = a.SectionName.toUpperCase();
let nameB = b.SectionName.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
console.table(items);
})();<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
但是不会在排序之前保持空对象的位置,我试图让它排序的方式是
{ID: 3, SectionName: "Alt"},
{ID: 20, SectionName: "Cabinet"},
{ID: 0, SectionName: ""},
{ID: 0, SectionName: ""},
{ID: 20, SectionName: "Cabinet"},
{ID: 2, SectionName: "Frame"},
{ID: 0, SectionName: ""},
{ID: 5, SectionName: "Lower"},
{ID: 0, SectionName: ""},
{ID: 0, SectionName: ""},
{ID: 0, SectionName: ""} ,
{ID: 4, SectionName: "Upper"}发布于 2021-03-24 22:04:23
您可以只过滤掉SectionName为空的那些项,对结果进行排序,然后将空的项重新插入到排序的输出中。
const items = [{"ID":20,"SectionName":"Cabinet"},{"ID":0,"SectionName":""},{"ID":0,"SectionName":""},{"ID":20,"SectionName":"Cabinet"},{"ID":2,"SectionName":"Frame"},{"ID":0,"SectionName":""},{"ID":3,"SectionName":"Alt"},{"ID":4,"SectionName":"Upper"},{"ID":0,"SectionName":""},{"ID":0,"SectionName":""},{"ID":0,"SectionName":""},{"ID":5,"SectionName":"Lower"}]
const sorted = items
.filter(({ SectionName }) => SectionName)
.sort((a, b) => a.SectionName.localeCompare(b.SectionName))
items.forEach((e, i) => {
if (!e.SectionName) sorted.splice(i, 0, e)
})
console.log(sorted)
发布于 2021-03-24 21:57:23
这是一种直接使用sort的方法,但是使用length和索引的Proxy来塑造访问。
const
sort = (array, sortFn, filterFn = _ => true) => {
const indices = [...array.keys()].filter(i => filterFn(array[i]));
new Proxy(array, {
get (target, prop) {
if (isFinite(prop)) return target[indices[prop]];
if (prop === 'length') return indices.length;
return target[prop];
},
set (target, prop, receiver) {
target[indices[prop]] = receiver;
return true;
}
})
.sort(sortFn);
return array;
},
items = [{ ID: 20, SectionName: "Cabinet" }, { ID: 0, SectionName: "" }, { ID: 0, SectionName: "" }, { ID: 20, SectionName: "Cabinet" }, { ID: 2, SectionName: "Frame" }, { ID: 0, SectionName: "" }, { ID: 3, SectionName: "Alt" }, { ID: 4, SectionName: "Upper" }, { ID: 0, SectionName: "" }, { ID: 0, SectionName: "" }, { ID: 0, SectionName: "" }, { ID: 5, SectionName: "Lower" }];
console.log(...sort(
items,
(a, b) => a.SectionName.localeCompare(b.SectionName),
({ SectionName }) => SectionName
));.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/66782498
复制相似问题