The question is published on by Tutorial Guruji team.
For my application I am passing in a string of numbers via query string and would like to find the median of all the numbers. This task is pretty simple when working with actual numbers, but considering that I am trying to find the median of a string of numbers, I must convert the string into an array, sort it, convert the nums to integers etc. How could I achieve this result? Here is how I tried to achieve this:
let nums = req.query let numArr = undefined for(let x in nums) { strX = nums[x].replace(/,/g, '').split('').sort(); numArr = strX.map(x => parseInt(x)) }
This method does not work for examples such as '5,7,9,1,12'
because it sorts the array like this [1,1,2,5,7,9]
Answer
Default behavior of Array.sort is to compare item as UTF16 strings. But you can override that behavior by using your compare function.
'5,7,9,1,12'.split(',').map(n => parseInt(n, 10)).sort((a,b) => a - b)