Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery equivalent of underscore.js' groupBy

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

Any workarounds?

Thanks

like image 756
DanC Avatar asked Jan 07 '13 20:01

DanC


People also ask

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How to do groupBy in JavaScript?

groupBy(dog => { return dog. breed; }); We can use the new groupBy function by calling it on the array instance, just like using a map , filter , or reduce function. groupBy takes a callback function which is called for each element in the array in ascending order.

What is the use of underscore in node js?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.


2 Answers

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.

like image 151
Bergi Avatar answered Oct 04 '22 01:10

Bergi


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');
});
like image 32
Riveascore Avatar answered Oct 04 '22 00:10

Riveascore