0

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]

2 Answers2

0

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.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • *"There is no way to get the original value back."* That statement is a bit too absolute. See for instance this related question: [How to convert floats to human-readable fractions?](https://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions) ([and this javascript answer](http://stackoverflow.com/a/681534/1934901)) or [Wikipedia: Continued fraction # Best rational approximations](https://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations) – Stef May 16 '22 at 19:44
  • @Stef You can not guarantee it was a reduced value. If you can guarantee it, then maybe there is a chance you can process it like crazy to get it. OR you just store the data correctly to start and there is nothing to do. – epascarello May 17 '22 at 12:58
0

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 );
PeterKA
  • 24,158
  • 5
  • 26
  • 48