考虑到我有一个如下所示的对象,其中可能有多个名称,并且“其他”可以出现在任何索引处,我如何对始终将“其他”作为第一个元素和其余元素的数组进行排序按字母顺序排列的名字?
var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
对于上面的示例数组,所需的结果是:
[
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' },
{ id: 2, name: 'Mary' },
{ id: 1, name: 'Paul' }
]
最佳答案
只需检查排序回调中的任一值是否为其他
- 如果a
是该值,则返回-1
,或者1
如果是 b
- 否则返回 a 和 b 的 localeCompare
friends.sort(({name: a}, {name:b}) => a == "The others" ? -1 : (b == "The others" ? 1 : a.localeCompare(b)));
该版本的“可读”且非 ES2015+ 版本
friends.sort(function (a, b) {
if (a.name == "The others") return -1;
if (b.name == "The others") return 1;
return a.name.localeCompare(b.name);
});
关于javascript - 对除一项之外的一组名称进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47666548/