jQuery equivalent of underscore.js' groupBy

偶尔善良 提交于 2019-12-06 03:07:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!