首页 > 解决方案 > 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,')

标签: javascriptnumbers

解决方案


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);


推荐阅读