0

Below given is the image of the code that was run in the console and the corresponding output is also shown.

While applying Sorting in Arrays in JS, how the 010 is converted to 8 and placed at last? whereas as per the rules it should come at the top of the sorted list. s

  • 010 is not a number. no number starts with 0. if you need to parse data to get it into the proper format, that's a map operation. if you console.log(Number(010)) or 010... it comes up with 8. basically you need to remove the zero... likely by an operation where you convert to string, and filter out leading zeros. – altruios Sep 22 '20 at 19:43
  • See https://stackoverflow.com/questions/6505033 and https://stackoverflow.com/questions/1063007 . – Luke Woodward Sep 22 '20 at 19:44

2 Answers2

1

First, "010" is converted to "8" because it is treated as Octal literal, you should not start an integer with a zero. Secondly if you want to sort an array of integers, you should follow this convention:

const arr = [34, 10, 11, 658, 1000]
console.log(arr.sort((a, b) => a - b ))
Tarreq
  • 1,282
  • 9
  • 17
0

010 is octal literal which gets converted to its equivalent decimal literal which is 8.

Joy Terence
  • 686
  • 5
  • 11
  • is there a good method for converted 010 into the number ten? – altruios Sep 22 '20 at 19:49
  • @altruios I would go with `parseInt(num.toString(), 10)` where `num` is `010` and probably going to be a string anyway. Passing `10` into `parseInt` tells it to use base 10, which should give you `10` rather than `8` – Brett East Sep 22 '20 at 20:28
  • I've tried useing those functions... but can't seem to convert array[i] if array[i] is a number that starts with 0... with no quotes. parseInt(num.toString(),10) still returns 8 when num is 010... it works if it has quotes around it (so it's a string) "010" – altruios Sep 22 '20 at 20:46