groupArray.js 830 B

12345678910111213141516171819202122232425262728293031323334
  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. * @typechecks
  8. */
  9. 'use strict';
  10. /**
  11. * Groups all items in the array using the specified function. An object will
  12. * be returned where the keys are the group names, and the values are arrays of
  13. * all the items in that group.
  14. *
  15. * @param {array} array
  16. * @param {function} fn Should return a string with a group name
  17. * @return {object} items grouped using fn
  18. */
  19. function groupArray(array, fn) {
  20. var ret = {};
  21. for (var ii = 0; ii < array.length; ii++) {
  22. var result = fn.call(array, array[ii], ii);
  23. if (!ret[result]) {
  24. ret[result] = [];
  25. }
  26. ret[result].push(array[ii]);
  27. }
  28. return ret;
  29. }
  30. module.exports = groupArray;