简体   繁体   English

按第一个字符排序数组,然后在 JavaScript 中编号

[英]Sort array by first character then number in JavaScript

There is list of object contains data like below: object 的列表包含如下数据:

[
    {name: 'Foo 1'},
    {name: 'Foo 14'},
    ..
    {name: 'Foo 2'},
    {name: 'Bar 1'},
    {name: 'Bar 15'},
    ...
    {name: 'Bar 2'},
]

I need to sort this as我需要将其排序为

[
    {name: 'Bar 1'},
    {name: 'Bar 2'},
    ...
    {name: 'Bar 15'},
    {name: 'Foo 1'},
    {name: 'Foo 1'},
    ...
    {name: 'Foo 12'},
]

With classic character sorting 'Foo 14' gets ahead of 'Foo 2' so I need to sort by letter and numbers.使用经典字符排序“Foo 14”领先于“Foo 2”,所以我需要按字母和数字排序。

value pattern: There might be multiple words but always ends with number like "word word.. number"值模式:可能有多个单词,但总是以数字结尾,如“word word.. number”

You could use Collator#compare for this.您可以为此使用Collator#compare The compare() method compares two strings according to the sort order of the Intl.Collator object. compare()方法根据Intl.Collator or object 的排序顺序比较两个字符串。 Just make sure you pass an options object where you set numeric to true :只要确保你传递了一个选项 object ,你将numeric设置为true

 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);

It appears that Intl.Collator is almost twice as fast as localeCompare .看来Intl.Collator几乎是localeCompare的两倍。 So, I would use @ZsoltMeszaros answer.所以,我会使用@ZsoltMeszaros 回答。


Using String.prototype.localeCompare() :使用String.prototype.localeCompare()

 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" }, ]; console.log(arr.sort((a,b)=>a.name.localeCompare(b.name,'en',{numeric: true})))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM