Is there a built in function in jQuery that does the equivalent of http://underscorejs.org/#groupBy ?
Any workarounds?
Thanks
Is there a built in function in jQuery that does the equivalent of http://underscorejs.org/#groupBy ?
Any workarounds?
Thanks
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');
});
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