Sorting a string of numbers received via query string Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Sorting a string of numbers received via query string without wasting too much if your time.

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)

We are here to answer your question about Sorting a string of numbers received via query string - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji