-2

leaderboard.txt content:

3, 503167934726311936
8, 737050574519967865
-10, 737050574519967865
23, 737050574519967865
19, 737050574519967865
-4, 737050574519967865
-14, 737050574519967865
27, 737050574519967865

unfinished javascript:

leaderboard = (fs.readFileSync('leaderboard.txt', 'utf-8'))
    //sorting leaderboard by number before comma
    fs.writeFileSync('leaderboard.txt', leaderboardSorted, 'utf8')

the result should look like this:

-14, 737050574519967865
-10, 737050574519967865
-4, 737050574519967865
3, 503167934726311936
8, 737050574519967865
19, 737050574519967865
23, 737050574519967865
27, 737050574519967865
Memag
  • 17
  • 5
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Jul 28 '20 at 17:07
  • Also explain exactly what you want to do such as what the final output should look like and any edge cases you can think of. – apena Jul 28 '20 at 17:10
  • @apena I edited the question – Memag Jul 28 '20 at 17:34

1 Answers1

0

After you have split up your string input and parseFloat'd it, you can pass a custom comparing funciton to the sort method, which will only compare the first element of each item. Then you can join them back together to write to the file.

const leaderboard = "3, 503167934726311936\n8, 737050574519967865\n-10, 737050574519967865\n23, 737050574519967865\n19, 737050574519967865\n-4, 737050574519967865\n-14, 737050574519967865\n27, 737050574519967865" // same as readFileSync

const data = leaderboard.split('\n').map(item => item.split(', ').map(parseFloat))

data.sort(([score1, id1], [score2, id2]) => score1 > score2 ? 1 : score1 < score2 ? -1 : 0)

leaderboardSorted = data.map(item => item.join(' ,')).join('\n')

console.log(leaderboardSorted)
Luke Storry
  • 6,032
  • 1
  • 9
  • 22
  • I just realized that the last 2 digits are always rounded. Do you have any idea why? – Memag Jul 28 '20 at 20:49
  • The largest number the JS can hold with normal floats is ` Number.MAX_SAFE_INTEGER`, or 9007199254740991. Basically anything more than 10 digits of precision is going to get messy. Think of another way of storing the data, you probbaly can store as a string, or you don't need that much precision. Or look into bigint: https://stackoverflow.com/questions/30678303/extremely-large-numbers-in-javascript – Luke Storry Jul 28 '20 at 22:55
  • Decided to slice the ID's in the middle and connect them later. – Memag Jul 29 '20 at 13:35