Search code examples
javascriptarrayssortingcoercion

Unexpected behavior with random array generation


I was trying to generate an array of random numbers between 10 and 1000 in descending ordered.

This is the code I wrote:

function GenerateRandomArray(){
  var array = [];

  for (var i = 0; i < 10; i++) {
    array[i] = Math.round(Math.random() * (1000 - 10 + 1) + 10);
  }
  return array.sort().reverse();
}

When run in the terminal, here are the results I get:

new GenerateRandomArray() => [ 924, 804, 79, 788, 585, 451, 267, 217, 153, 135 ]

new GenerateRandomArray() => [ 869, 697, 647, 59, 458, 30, 291, 157, 112, 111 ]

new GenerateRandomArray() => [ 999, 98, 872, 823, 705, 418, 404, 306, 259, 20 ]

new GenerateRandomArray() => [ 688, 666, 664, 615, 580, 565, 336, 304, 250, 246 ]

new GenerateRandomArray() => [ 912, 906, 759, 690, 673, 481, 429, 355, 19, 103 ]

Why some arrays are in the right format and some others have a non ordered number in the middle of it ?

I tested:

  • converting numbers to strings
  • accessing the unordered element in the array (it gives the same number - obviously)
  • doing it with a function instead of a constructor

This doesn't change the weird result.

Am I missing something like a JS coercive property or something ?

Thanks :)


Solution

  • By default the sort function sorts in alphanumeric/alphabetical order (i.e., "string sort"). As strings go, "aaa" comes before "b", and similarly "111" comes before "2".

    To instead sort by numeric value, you can provide your own compare function.

    array.sort(function(a, b) { 
        return a - b;
    });