Good afternoon, please help solve the problem Random order in an array.
I understand all the terms, etc., but I CAN'T UNDERSTAND THE LOGIC to solve this problem:

Use the sort function to “shake up” the elements of an array in a random order.

spoiler
var arr=[1, 2, 3, 4, 5];

arr.sort(your function);

alert(arr);//elements in random order, for example[3,5,1,2,4]


I know that here the premium method is Math.random() - it returns values ​​from 0 to 1.But how can this help me here?
  • Annoying5 dear user, we strongly recommend once again to pay close attention to clause 3.1 of the service policy(and, in particular, on its last paragraph).
    Otherwise, your questions will be deleted due to spam tag, and systematic violations will lead to account lockout.
    – Bionic Fantasy Apr 4 '19 at 15:35
  • Tell me please the sequence of actions ??
    Why are there two arguments A and B.What for in the function 0.5 value ??
    It should return a random value from - 0.5 to 0.5.But if it returns 0.35151 and what's next?
    I can't understand how this value changes the array !!(((
    – Annoying5 Apr 4 '19 at 15:50

1 Answers 1

var arr=[1, 2, 3, 4, 5];

function compareRandom(a, b) {
  return Math.random() - 0.5;
}

arr.sort(compareRandom);
  • I know !!!
    Tell me please the sequence of actions ??
    Why are there two arguments A and B.What is the meaning of 0.5 in the function ??
    It should return a random value from - 0.5 to 0.5.But if it returns 0.35151 and what's next?
    I can't understand how this value changes the array !!(((
    – Annoying5 Apr 4 '19 at 15:39
  • Annoying5,

    https://habr.com/ru/post/358094/
    – Neon6 Apr 4 '19 at 15:43
  • Neon6, I’m interested in an explanation for this particular task.
    If you do not complicate.THANK YOU
    – Annoying5 Apr 4 '19 at 15:49
  • I would also add toFixed(1) in the code to get zero.
    Annoying5, read about the work of the sort method - learn.javascript.ru/array- methods #sortirovka-metod...
    – Cruel37 Apr 4 '19 at 17:20