Sort Array of numeric & alphabetical elements (Natural Sort)

后端 未结 8 1089
独厮守ぢ
独厮守ぢ 2020-12-03 14:48

Suppose I have an array

var arr = [1,5,\"ahsldk\",10,55,3,2,7,8,1,2,75,\"abc\",\"huds\"];

and I try sorting it, I get something like ...

8条回答
  •  广开言路
    2020-12-03 15:07

    You could do this in one line using String.prototype.localCompare() and get the result you are looking for. Note that the numeric collation option is enabled.

    var arr = [1,5,"ahsldk",10,55,3,2,7,8,1,2,75,"abc","huds"];
    
    arr.sort((a,b) => ("" + a).localeCompare(b, undefined, {numeric: true}));
    
    console.log(arr);
    // [1, 1, 2, 2, 3, 5, 7, 8, 10, 55, 75, "abc", "ahsldk", "huds"]

    Maybe add some logic to handle nulls.

提交回复
热议问题