1

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]

2
  • 1. Is req.query a string of numbers (e.g. 5,7,9,1,12)? 2. You are overwriting numArr for every number, which doesn't seem like what you want to do. Are you intending for numArr to be the string of numbers converted into integers? Commented Apr 6, 2021 at 20:24
  • When you replace the commas, the result is '579112'. When you split this by '', the result is '5,7,9,1,1,2'. Commented Apr 6, 2021 at 20:25

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Why n => parseInt(n, 10) instead of Number or even just n=>+n?
OK as long as the array doesn't contain Infinity or NaN.
Cause +n is a trick. parseInt is explicit.
1

You could take a the string as part of a JSON string and get an array of numbers, sort it and get the median value, depending of the length of the array.

const
    string = '5,7,9,1,12',
    array = JSON
        .parse(`[${string}]`)
        .sort((a, b) => a - b),
    median = array.length % 2
        ? array[array.length >> 1]
        : (array[(array.length >> 1) - 1] + array[array.length >> 1]) / 2;

console.log(...array);
console.log(median);

4 Comments

What if string contains duplicate numbers?
@GirkovArpa, it does not matter for getting a media, if a number occures more then one time.
The custom sorting comparator function is redundant as the default behaviour for sort() on numbers is to sort them in ascending order.
@AnsonMiu, no, because the Array#sort without callback sorts strings, so you get 11 < 2 and this is not wanted.
0

You should do this:

 let nums = req.query
 let numArr = undefined

 for(let x in nums) {
     strX = nums[x].split(',').map(x => parseInt(x)).sort((x,y) => x - y);
 }

However I think the loop is redundant, though I haven't tested it. That is, you can do

 let nums = req.query
 let numArr = nums.split(",").map(x => parseInt(x)).sort((x,y) => x - y);

2 Comments

Should do .sort() after .map(), because ["1", "2", "12"] will be sorted as ["1", "12", "2"] in their string representations, as supposed to [1, 2, 12] in their numerical forms.
+as per the comment from @Nina Scholz , the sort() function will sort by string lexicographical order, so a custom comparator .sort((x, y) => x - y) is needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.