我有一系列圣经经文,我试图按照经文的自然顺序进行排序。
数组如下所示:
let array = ["1.2","1.3","1.19","2.25","1.0"]
我期待的最终结果是:
1.0, 1.2, 1.3, 1.19, 2.25
任何指针都欢迎,我还没有设法完成排序函数,在排序小数的另一端的其他所有内容之前对第一个数字进行排序。
我认为我目前需要改进的方法是:
x.sort(function(a,b){
let y = a.split(".")[1]
let x = b.split(".")[1]
return a-b && y - x;
})
答案 0 :(得分:0)
let array = ["1.2","1.3","1.19","2.25","1.0"];
// split the number into the integer part and decimal part
splits = array.map(x => ({
val: x,
int: Number(x.split(".")[0]),
dec: Number(x.split(".")[1])
}));
splits.sort(function(a, b) {
// compare the integer part first, if equal, compare decimal part
return (a.int === b.int)?(a.dec - b.dec):(a.int - b.int);
});
sorted = splits.map(x => x.val);
console.log(sorted);
对阵列进行排序的另一个选择:
let array = ["1.2","1.3","1.19","2.25","1.0"];
array.sort(function(a, b) {
a_split = a.split(".").map(Number);
b_split = b.split(".").map(Number);
return (a_split[0] === b_split[0])?(a_split[1] - b_split[1]):(a_split[0] - b_split[0]);
})
console.log(array);