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