Sort Array of Objects having decimal/dotted numbers [duplicate]

独自空忆成欢 提交于 2021-02-17 06:59:47

问题


how can I sort the below array in ascending order in JS?

let obj_list = [{Sno:"1"},{Sno:"4"},{Sno:"3"},{Sno:"9"},{Sno:"9.1"},
                {Sno:"9.2"},{Sno:"9.6"},{Sno:"9.3"},{Sno:"9.10"},
                {Sno:"9.11"},{Sno:"9.13"},{Sno:"9.12"}];

I tried the normal sort function as written below, but the output was coming incorrect

obj_list.sort(function(a,b){
return a.Sno - b.Sno;
});

UPDATING the Post:

I am expecting the output as:

[{Sno:"1"},{Sno:"3"},{Sno:"4"},{Sno:"9"},{Sno:"9.1"},
{Sno:"9.2"},{Sno:"9.3"},{Sno:"9.6"},{Sno:"9.10"},
{Sno:"9.11"},{Sno:"9.12"},{Sno:"9.13"}]

回答1:


Here your answer please check it thanks.

let obj_list = [{ Sno: "1" }, { Sno: "4" }, { Sno: "3" }, { Sno: "9" }, { Sno: "9.1" },
    { Sno: "9.2" }, { Sno: "9.6" }, { Sno: "9.3" }, { Sno: "9.10" },
    { Sno: "9.11" }, { Sno: "9.13" }, { Sno: "9.12" }
];



obj_list.sort(function(a, b) {
    var x = a["Sno"];
    var y = b["Sno"];
    return x - y;
});
var without_decimal = obj_list.filter(o => o.Sno.split(".").length == 1);
obj_list = obj_list.filter(o => o.Sno.split(".").length > 1).sort(function(a, b) {
    var x = a["Sno"].split(".")[1] + "0";
    var y = b["Sno"].split(".")[1] + "0";
    return x - y;
});
var result = without_decimal.concat(obj_list);
console.log(result)


来源:https://stackoverflow.com/questions/66167827/sort-array-of-objects-having-decimal-dotted-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!