javascript - Javascript - 如何返回数组中最大的四个数字?
问题描述
我有一个数字字符串数组。我正在尝试取回数组中最大的 4 个数字。
const data = [
"1,203,291",
"2,301,291",
"643,092",
"1,391,290",
"32,309",
"3,391"
]
我正在尝试返回2,301,291, 1,391,290, 1,203,291, 643,092
我首先删除字符串中的逗号并将其转换为数字。
let topArr = data.map(e => Number(e.replace(/(,\s*)+/g, '').trim()));
然后创建另一个等于最大数字集的变量。
let topValues = Math.max(...topArr)
//bring back the commas that were removed to append values with commas
String(topValues).replace(/(.)(?=(\d{3})+$)/g, '$1,')
我用过Math.Max
,但只返回最大的数字,2,301,291
有没有办法改变 Math.Max 以获得前 4 名?
这是我的完整代码:
const data = [
"1,203,291",
"2,301,291",
"643,092",
"1,391,290",
"32,309",
"3,391"
]
let topArr = data.map(e => Number(e.replace(/(,\s*)+/g, '').trim()));
let topValues = Math.max(...topArr)
//bring back the commas that were removed to append values with commas
String(topValues).replace(/(.)(?=(\d{3})+$)/g, '$1,')
解决方案
const data = [
"1,203,291",
"2,301,291",
"643,092",
"1,391,290",
"32,309",
"3,391"
];
let result = data.map(el => Number(el.split(",")
.join("")))
.sort((a,b) => b - a)
.splice(0, 4)
console.log(result);
推荐阅读
- git - 提交后挂钩中的“git send-email”不适用于 Github Desktop
- python - Pyro4:反序列化 protobuf 类
- android - Recyclerview 仅第一次显示数据
- asynchronous - Google AppMaker 中的异步函数
- scala - 从嵌套类型获取子类型
- regex - 如何从电子邮件正文中复制特定文本?
- python - Selenium with Firefox-Gracefully 将控制权留给用户
- linux - 在 Linux 中搜索与特定模式匹配的所有子文件夹中的文件
- android - 在 mapbox 的 Log 控制台中获取经纬度
- javascript - HTML - 退出全屏视频并暂停在 Google Chrome 上不起作用