使用javascript以特定顺序对具有十进制值的数组进行排序 [英] sorting array with decimal value in specific order using javascript

查看:68
本文介绍了使用javascript以特定顺序对具有十进制值的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

let arr = ['100.12', '100.8', '100.11', '100.9'];

排序后得到输出:

'100.11',
'100.12',
'100.8',
'100.9',

但是我希望它能像页面索引一样进行排序:

But I want it to be sorted like page indexing :

'100.8',
'100.9',
'100.11',
'100.12',


我几乎没有好的解决方案,但是他们缺乏一个地方,例如: arr1 = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9']


I have got few good solution but they are lacking at one place ex: arr1 = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9']

结果将是:

["77.8", "77.9", "77.11", "77.12", "77", "88", "100.8", "100.11", "100.12", "100", "100.9", "119", "120"]

这里应该是:

[ "77", "77.8", "77.9", "77.11", "77.12", "88", "100", "100.8", "100.11", "100.12", "100.9", "119", "120"]

推荐答案

您可以将string#localeComparenumeric属性一起使用,以根据数值对数组进行排序.

You can use string#localeCompare with numeric property to sort your array based on the numeric value.

let arr = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9'];
arr.sort((a, b) => a.localeCompare(b, undefined, {numeric: true}))
console.log(arr)

这篇关于使用javascript以特定顺序对具有十进制值的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆