Unexpected behavior when generating random arrays

I tried to create an array of random numbers from 10 to 1000 in descending order.

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 running in the terminal, here are the results that 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 are some arrays in the correct format, and some others have an unordered number in the middle ?

I tested:

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

This does not change the strange result.

Am I missing something like a JS forced property or something else?

Thanks:)

+5
source share
3 answers

By default, the sort function is sorted in alphanumeric / alphabetical order (ie, "sort the string"). As the lines go, "aaa" is preceded by "b", and similarly, "111" is preceded by "2".

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

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

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

The default sort order corresponds to Unicode string codes.

If compareFunction is not provided, elements are sorted by converting them into strings and comparing strings in Unicode code sequence order. For example, “Banana” comes before “cherry”. In numerical sorting, 9 comes up to 80, but since numbers are converted to strings, "80" precedes "9" in Unicode order.

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

One more thing:

it is a function that returns an array of random numbers (sorted), so it cannot be used with the new keyword, because you are not using it as a constructor. Besides personal preferences, I could call the function getRandomNumberArray or getArrayOfRandomNumbers .

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

+1
source
 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
source

Source: https://habr.com/ru/post/1247524/


All Articles