2 回答
TA贡献1848条经验 获得超6个赞
这可能不是最有效的方法,但我发现下面的代码很容易理解。请注意,排序需要按照与列出它们的顺序相反的顺序进行。
const obj = {
"data": [
{
"ownerName": "Bob",
"dogCode": "5",
"dogName": "Rex"
},
{
"ownerName": "John"
},
{
"ownerName": "Alisha",
"dogCode": "3",
"dogName": "Moon"
},
{
"ownerName": "Darren",
"dogCode": "4",
"dogName": "Bos"
},
{
"ownerName": "Josh"
},
{
"ownerName": "Cerq"
}
]
};
const byPropExists = prop => (a, b) => {
if (a[prop] !== undefined && b[prop] === undefined) return -1;
if (a[prop] === undefined && b[prop] !== undefined) return 1;
return 0;
}
const byPropValue = prop => (a, b) => a[prop]?.localeCompare(b[prop])
// Note the reverse order of your sorts
console.log(obj.data
.sort(byPropValue('dogName'))
.sort(byPropValue('ownerName'))
.sort(byPropExists('dogCode'))
);
TA贡献1854条经验 获得超8个赞
您可以将未定义检查的增量作为排序值,并按数字增量或String#localeCompare
字符串进行排序。
const data = [{ ownerName: 'Bob', dogCode: 5, dogName: 'Rex' }, { ownerName: 'John' }, { ownerName: 'Alisha', dogCode: 3, dogName: 'Moon' }, { ownerName: 'Darren', dogCode: 4, dogName: 'Boss' }, { ownerName: 'Josh' }, { ownerName: 'Cerq' }];
data.sort((a, b) =>
(a.dogCode === undefined) - (b.dogCode === undefined) ||
(a.ownerName === undefined) - (b.ownerName === undefined) ||
(a.dogName === undefined) - (b.dogName === undefined) ||
(a.ownerName || '').localeCompare(b.ownerName || '') ||
a.dogCode - b.dogCode ||
(a.dogName || '').localeCompare(b.dogName || '')
);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报