groupArray.js.flow 860 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule groupArray
  8. * @typechecks
  9. */
  10. 'use strict';
  11. /**
  12. * Groups all items in the array using the specified function. An object will
  13. * be returned where the keys are the group names, and the values are arrays of
  14. * all the items in that group.
  15. *
  16. * @param {array} array
  17. * @param {function} fn Should return a string with a group name
  18. * @return {object} items grouped using fn
  19. */
  20. function groupArray(array, fn) {
  21. var ret = {};
  22. for (var ii = 0; ii < array.length; ii++) {
  23. var result = fn.call(array, array[ii], ii);
  24. if (!ret[result]) {
  25. ret[result] = [];
  26. }
  27. ret[result].push(array[ii]);
  28. }
  29. return ret;
  30. }
  31. module.exports = groupArray;