Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast grouping of a javascript array

I have an array of a couple thousand strings

['7/21/2011', '7/21/2011', '7/21/2011', '7/20/2011', etc]

I am currently, running this code to group by the string and get the max group value:

var max = 0;
var group = {};
arr.map(function (value) {
  if (group[value]) {
    group[value]++;
  } else {
    group[value] = 1;
  }
  max = Math.max(max, group[value]);
});

Are there any improvements to make this code run faster?

EDIT: The results are in: http://jsperf.com/javascript-array-grouping2

EDIT EDIT: that test was flawed. Mike Samuel's code was the fastest.

6000 entries test -> http://jsperf.com/javascript-array-grouping2

10K entries test -> http://jsperf.com/javascript-array-grouping

like image 932
Joe Avatar asked Jul 21 '11 19:07

Joe


1 Answers

If you're sure this is a hotspot and speed is really important, I would try to cut out several thousand function calls by inlining max and map.

You can also make the body of your function faster by cutting out a comparison.

var max = 0;
var group = {};
for (var i = arr.length; --i >= 0;) {
  var value = arr[i];
  var n = group[value] = 1 - -(group[value] | 0);
  if (n > max) { max = n; }
}

The best thing to do is measure on the browsers you care about.

like image 158
Mike Samuel Avatar answered Sep 22 '22 22:09

Mike Samuel