在 JavaScript 中按第一个字符然后数字对数组进行排序

TyF*_*ude 4 javascript reactjs

有包含数据的对象列表,如下所示:

[
    {name: 'Foo 1'},
    {name: 'Foo 14'},
    ..
    {name: 'Foo 2'},
    {name: 'Bar 1'},
    {name: 'Bar 15'},
    ...
    {name: 'Bar 2'},
]
Run Code Online (Sandbox Code Playgroud)

我需要将其排序为

[
    {name: 'Bar 1'},
    {name: 'Bar 2'},
    ...
    {name: 'Bar 15'},
    {name: 'Foo 1'},
    {name: 'Foo 1'},
    ...
    {name: 'Foo 12'},
]
Run Code Online (Sandbox Code Playgroud)

通过经典的字符排序,“Foo 14”领先于“Foo 2”,因此我需要按字母和数字进行排序。

值模式:可能有多个单词,但总是以数字结尾,例如“word word .. number”

Zso*_*ros 8

你可以用Collator#compare这个。该compare()方法根据对象的排序顺序比较两个字符串Intl.Collator。只需确保传递一个选项对象,将其设置numerictrue

const collator = new Intl.Collator("en", {
  numeric: true,
  sensitivity: "base",
});

const arr = [
  { name: "Foo 1" },
  { name: "Baz 21" },
  { name: "Foo 14" },
  { name: "Foo 2" },
  { name: "Bar 1" },
  { name: "Baz 10" },
  { name: "Bar 15" },
  { name: "Bar 2" },
  { name: "Baz 1" },
  { name: "Baz 2" },
];

const sorted = arr.sort((a, b) => collator.compare(a.name, b.name));

console.log(sorted);
Run Code Online (Sandbox Code Playgroud)