5

Is there a built in function in jQuery that does the equivalent of http://underscorejs.org/#groupBy ?

Any workarounds?

Thanks

DanC
  • 8,595
  • 9
  • 42
  • 64

3 Answers3

7

No. jQuery was not made for data handling, but for DOM, Ajax and Animations - those utility functions as each, map or grep which are needed internally suck.

Use Underscore, there is nothing wrong with it! If you don't want to load the whole script, you can easily copy the groupby function from the source to wherever you need it. Don't forget to add a comment on its origin.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

Here is a jQuery adaptation of squint's native Javascript answer:

$.fn.groupBy = function(predicate) {
  var $array = $(this),
      grouped = {};

  $.each($array, function (idx, obj) {
    var $obj = $(obj);
        groupKey = predicate($obj);
    if (typeof(grouped[groupKey]) === "undefined") {
      grouped[groupKey] = $();
    }
    grouped[groupKey] = grouped[groupKey].add($obj);
  });

  return grouped;
}

^This returns a hash of { key_name: jQueryObjects }


And usage, in this case, to group elements ($yourElements) by the HTML name attribute:

var groupedByName = $yourElements.groupBy(function (obj) {
  return $(obj).attr('name');
});
Community
  • 1
  • 1
Riveascore
  • 1,724
  • 4
  • 26
  • 46
0

I've used this, and it worked for me perfectly

function groupBy(array, keyOrIterator) {
  var iterator, key;

  // use the function passed in, or create one
  if(typeof key !== 'function') {
    key = String(keyOrIterator);
    iterator = function (item) { return item[key]; };
  } else {
    iterator = keyOrIterator;
  }

  return array.reduce(function (memo, item) {
    var key = iterator(item);
    memo[key] = memo[key] || [];
    memo[key].push(item);
    return memo;
  }, {});
}

from Link

AhmadMM
  • 371
  • 4
  • 16