Home > Net >  Is it possible to sort array with some "between" numbers?
Is it possible to sort array with some "between" numbers?

Time:05-17

Is it possible, somehow, to sort array with some "between" numbers?

[31, 33/34, 34, 29].sort((a, b) => a.toString().localeCompare(b.toString()))

//to return [29, 31, 33/34, 34] instead [0.9705882352, 29, 31, 34]

CodePudding user response:

As mentioned in the comments, the only way this will work is if you use string to capture the numbers. The engine is going to store your 33/34 as the decimal. There is no way to get the original value back.

Doing it is just a simple parse and sort.

var nums = ['31', '33/34', '34', '29']

nums.sort((a, b) => Number(a.split('/')[0]) - Number(b.split('/')[0]));

console.log(nums);

Now you may need to add more logic if you can have multiple numbers to push the 33/34 to the right spot. Not knowing all of the use cases, I am going to not try to guess.

CodePudding user response:

When converting to string your are converting the fraction 33/34 (=0.9705882352). That's all that's visible the JS interpreter: it does not matter whether you provided 0.9705882352 or 33/34 or 66/68. So as indicated by @ninascholz & @epascarello, you have to start off with strings. With strings, your code should work fine as in the demo below:

const nums = ['31', '33/34', '34', '29']

nums.sort((a, b) => a.localeCompare(b));

console.log( nums );

  • Related