var arr = ['bla','hahahah','123456789','1','ew']; function lensort(a,b) { var s1 = "" + a; // Что это за переменная? var s2 = "" + b; // а это? if(s1.length < s2.lenght){ return false; } else if(s1.length > s2.length){ return true; } } 
 console.log(arr.sort(lensort)) --> arr["1", "ew", "bla", "hahahah", "123456789"] 

How does this function sort an array by the length of its elements?

Closed due to the fact that off-topic participants are Alexey Shimansky , AK , Vadim Ovchinnikov , aleksandr barakin , Kromster 11 Jan '17 at 4:03 .

  • Most likely, this question does not correspond to the subject of Stack Overflow in Russian, according to the rules described in the certificate .
If the question can be reformulated according to the rules set out in the certificate , edit it .

2 answers 2

As described by Grundy, the main point here is the use of the sort method. In essence, the lensort function is a “selection criterion”. Those. the sort method gives the lensort method 2 values. Those. in the first step, it gave the values arr[0] and arr[1] ( 'bla','hahahah') . Next, I will mark in the code what and how:

  function lensort(a,b) { var s1 = "" + a; // Это первый параметр или arr[0] var s2 = "" + b; // это второй параметр или arr[1] // по сути тут мы однозначно получаем строки s1 и s2 типа string if(s1.length < s2.lenght){ return false; // элементы на своих позициях по возрастанию } else if(s1.length > s2.length){ return true; // элемент arr[0] больше и его мы будет "двигать" вправо по массиву } } 

As a result, when your lensort function returns true , the sort method makes the decision that the first element is “larger” than the second and mixes it to the right. And then the iteration moves further and compares the other 2 values, for example arr[1] and arr[2] (depending on the algorithm, the first element can be compared with all remaining ones, or using the bubble method, etc., see "sorting algorithms")

     var s1 = "" + a; 

    they do it to get a string anyway, that is, if there is 123456789 there, then it can be both string and int, so that it definitely has the type string do such a clever operation, there are many such tricks, for example, if we want to always have some value then we do it

     var s = object.param || "строка"; 

    and then even if string will be object.param will not exist in the variable s will be the value "string" and not undefined.

    • '123456789' - This is always a string - Grundy