对除一项之外的一组名称进行排序

Vin*_*ana 1 javascript arrays sorting

考虑到我有一个如下所示的对象,其中可能有多个名称,并且“其他”可以出现在任何索引处,我如何对始终将“其他”作为第一个元素和其余名称的数组进行排序按字母顺序排序?

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
Run Code Online (Sandbox Code Playgroud)

对于上面的示例数组,所需的结果将是:

[
   { id: 3, name: 'The others' }, 
   { id: 4, name: 'John' }, 
   { id: 2, name: 'Mary' }, 
   { id: 1, name: 'Paul' }
]
Run Code Online (Sandbox Code Playgroud)

Jar*_*a X 5

只需检查排序回调中的任一值The others--1如果a是则1返回b,否则返回 a 和 b 的 localeCompare

friends.sort(({name: a}, {name:b}) => a == "The others" ? -1 : (b == "The others" ? 1 : a.localeCompare(b)));
Run Code Online (Sandbox Code Playgroud)

其“可读”和非 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);
});
Run Code Online (Sandbox Code Playgroud)