groupByEveryN.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  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. * @format
  8. * @flow strict
  9. */
  10. /**
  11. * Useful method to split an array into groups of the same number of elements.
  12. * You can use it to generate grids, rows, pages...
  13. *
  14. * If the input length is not a multiple of the count, it'll fill the last
  15. * array with null so you can display a placeholder.
  16. *
  17. * Example:
  18. * groupByEveryN([1, 2, 3, 4, 5], 3)
  19. * => [[1, 2, 3], [4, 5, null]]
  20. *
  21. * groupByEveryN([1, 2, 3], 2).map(elems => {
  22. * return <Row>{elems.map(elem => <Elem>{elem}</Elem>)}</Row>;
  23. * })
  24. */
  25. 'use strict';
  26. function groupByEveryN<T>(array: Array<T>, n: number): Array<Array<?T>> {
  27. const result = [];
  28. let temp = [];
  29. for (let i = 0; i < array.length; ++i) {
  30. if (i > 0 && i % n === 0) {
  31. result.push(temp);
  32. temp = [];
  33. }
  34. temp.push(array[i]);
  35. }
  36. if (temp.length > 0) {
  37. while (temp.length !== n) {
  38. temp.push(null);
  39. }
  40. result.push(temp);
  41. }
  42. return result;
  43. }
  44. module.exports = groupByEveryN;