0
alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""));

This is probably one of the shortest ways to generate a 10-digit number in JavaScript that contains 10 digits from 0 to 9 in the randomized order. Example: 7205169483.

split("")//OK, it splits by chars because of empty separator
.sort(function(){return .5-Math.random()})
.join("")//joins with empty string as a separator

Why doesn't {return Math.random()} work?

How many times .sort() is executed - ten or one?

Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

1 Answers1

0

As it has been said in the comments by @elclanrs, sort expects a callback function that will take two elements a and b and compare them. This function must return a negative number if a < b, 0 if a == b and a positive number otherwise.

The function sort will be called a number of times that depends on the implementation of the sorting algorithm. You can find more information in this question.

In your example, 0.5 - Math.Random() will return a negative, or a positive number, because Math.Random() returns a value between 0 and 1.

Community
  • 1
  • 1
Martin
  • 1,868
  • 1
  • 15
  • 20