Sort an array of over 10 objects in Chrome

[
{"tag":"fujairah","count":1},
{"tag":"worldwide","count":3},
{"tag":"saudi","count":1},
{"tag":"miami","count":1},
{"tag":"rwo-dealer","count":7},
{"tag":"new york","count":2},
{"tag":"surabaya","count":1},
{"tag":"phillippines","count":1},
{"tag":"vietnam","count":1},
{"tag":"norway","count":1},
{"tag":"x","count":1}
].sort(function(a,b){return a.tag>b.tag})

Sorting an array of 10 objects works great, as soon as the number of objects exceeds 10, sorting is not performed in Chrome for Mac. Safari is not suitable for any array size. (Works great in Firefox)

What is the correct way to sort arrays of objects using javascript?

+4
source share
2 answers

, . . 1 ( , "", ), -1 ( ) 0 ( ). - :

.sort(function(a, b) {
    return a.tag > b.tag ? 1 : (a.tag < b.tag ? -1 : 0);
});

.

+2

, , - , 0.

. ECMA . , , , 0, .

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11

(.. , , ). comparefn undefined, , x y , x < y, , x = y, , x > y.

Chrome ( ). , , , . , . .

Chromium length <= 10 .

https://cs.chromium.org/chromium/src/v8/src/js/array.js?l=707&rcl=9c7cccf55126353a101f194bcf1f8826bc263804

function InnerArraySort(array, length, comparefn) {
  // In-place QuickSort algorithm.
  // For short (length <= 10) arrays, insertion sort is used for efficiency.
  ...
  if (to - from <= 10) {
    InsertionSort(a, from, to);
    return;
  }
 ...
+1

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


All Articles