Is there a built in function in jQuery that does the equivalent of http://underscorejs.org/#groupBy ?
Any workarounds?
Thanks
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
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.
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.
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.
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;
}
And usage, in this case, to group elements ($yourElements
) by the HTML name
attribute:
var groupedByName = $yourElements.groupBy(function (obj) {
return $(obj).attr('name');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With