5

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 :)

GMchris
  • 5,439
  • 4
  • 22
  • 40
Stan Amsellem
  • 503
  • 1
  • 5
  • 16

3 Answers3

3

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;
});
Thomas
  • 429
  • 2
  • 10
2
function GenerateRandomArray(){
  var arr = [];

  for (var i = 0; i < 10; i++) {
    arr.push(Math.round(Math.random() * 1000));
  }
  arr.sort(function compareNumbers(a, b) {
    return a - b;
  });
  return arr;
}
1

use

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

or simply:

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

Docs:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Quoted:

The default sort order is according to string Unicode code points.

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

To compare numbers instead of strings, the compare function can simply subtract b from a.

One more thing:

this is a function that returns an array of random numbers (sorted), so it should not be used with the new keyword, because you are not using it as a constructor. Also, personal preferences, I might have named the function getRandomNumberArray or getArrayOfRandomNumbers.

Sample: https://jsfiddle.net/cmfoo49m/2/

Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740