问题
Is there a built in function in jQuery that does the equivalent of http://underscorejs.org/#groupBy ?
Any workarounds?
Thanks
回答1:
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.
回答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');
});
来源:https://stackoverflow.com/questions/14203778/jquery-equivalent-of-underscore-js-groupby