how to sort strings in javascript numerically

前端 未结 7 1423
一个人的身影
一个人的身影 2021-02-14 12:48

I would like to sort an array of strings (in javascript) such that groups of digits within the strings are compared as integers not strings. I am not worried about signed or fl

7条回答
  •  有刺的猬
    2021-02-14 12:55

    Another variant is to use an instance of Intl.Collator with numeric option:

    var array = ["a100","a20","a3","a3b","a3b100","a3b20","a3b3","!!","~~","9","10","9.5"];
    var collator = new Intl.Collator([], {numeric: true});
    array.sort((a, b) => collator.compare(a, b));
    console.log(array);

提交回复
热议问题