Strange JavaScript array sorting behavior

While trying to sort a JavaScript array, I came across strange behavior.

var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k'];

arr.sort(function (a, b) {
  console.log(a, b);
  if (a.length < b.length) return 1;
  else if (a.length > b.length) return -1;
  else return 0;
});
Run codeHide result

Works well in this case, returning me the same array.

The console is as follows:

enter image description here

But when I try to do it below

var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k', 'l'];

Gives me this

enter image description here

I canโ€™t understand why this is happening.

PS. I am writing this custom sort by checking the length of the elements because I need an array that has its elements sorted by length.

+3
source share
1 answer

ECMAScript (Array.prototype.sort). , "". Array # sort , 0. InsertionSort MergeSort (Apple Mozilla) , QuickSort (Google Chrome) ( 90). Chrome InsertionSort, 10 .

, Safari Firefox ["sed", "dolor", "ipsum", "foo", "bar", "cat", "sit", "man", "lorem", "amet", "maecennas"] ( ) , "sed" , Chrome , , "cat" -. Chrome ...

, , , MergeSort, .

+2

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


All Articles