_.chunk

Creates an array of elements split into groups the length of size.

  1. // Underscore/Lodash
  2. _.chunk(['a', 'b', 'c', 'd'], 2);
  3. // => [['a', 'b'], ['c', 'd']]
  4.  
  5. _.chunk(['a', 'b', 'c', 'd'], 3);
  6. // => [['a', 'b', 'c'], ['d']]
  7.  
  8.  
  9. // Native
  10.  
  11. const chunk = (input, size) => {
  12. return input.reduce((arr, item, idx) => {
  13. return idx % size === 0
  14. ? [...arr, [item]]
  15. : [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
  16. }, []);
  17. };
  18.  
  19. chunk(['a', 'b', 'c', 'd'], 2);
  20. // => [['a', 'b'], ['c', 'd']]
  21.  
  22. chunk(['a', 'b', 'c', 'd'], 3);
  23. // => [['a', 'b', 'c'], ['d']]

Browser Support for Spread in array literals

ChromeEdgeFirefoxIEOperaSafari
46.0 ✔12.0 ✔16.0 ✔37.0 ✔8.0 ✔