Javascript - How to return the largest four numbers in an array?

Viewed 339

I have an array of strings that are numbers. I am attempting to get back the largest 4 numbers in my array.

  const data = [
         "1,203,291",
         "2,301,291", 
         "643,092", 
         "1,391,290", 
         "32,309", 
         "3,391" 
                ]

I am attempting to return 2,301,291, 1,391,290, 1,203,291, 643,092

I first start off by removing the commas in a string and converting it into a number.

let topArr = data.map(e => Number(e.replace(/(,\s*)+/g, '').trim()));

Then create another variable which equals the max set of numbers.

 let topValues = Math.max(...topArr)
//bring back the commas that were removed to append values with commas
  String(topValues).replace(/(.)(?=(\d{3})+$)/g, '$1,')

I've used Math.Max but that only returns the largest number which is 2,301,291 is there a way to alter Math.Max in order to receive the top 4?

Here is my code in full code:

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,')
3 Answers

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

Why not sort them after conversion to numbers and retrieve the last four numbers?

sort them in descending order then use slice to get first 4 and then again use map and inside callback use the code to add thousand separator

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()))
    // order in descending order
 .sort((a, b) => {
  return b - a;
 })
    // get the first 4
 .slice(0, 4)
    // return a new array & inside callback to add comma separator 
 .map((item) => {
  return String(item).replace(/(.)(?=(\d{3})+$)/g, '$1,')

 });

console.log(topArr)

Related