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:
This doesn't change the weird result.
Am I missing something like a JS coercive property or something ?
Thanks :)
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;
});
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With