_.chunk
Creates an array of elements split into groups the length of size.
- // Underscore/Lodash
- _.chunk(['a', 'b', 'c', 'd'], 2);
- // => [['a', 'b'], ['c', 'd']]
- _.chunk(['a', 'b', 'c', 'd'], 3);
- // => [['a', 'b', 'c'], ['d']]
- // Native
- const chunk = (input, size) => {
- return input.reduce((arr, item, idx) => {
- return idx % size === 0
- ? [...arr, [item]]
- : [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
- }, []);
- };
- chunk(['a', 'b', 'c', 'd'], 2);
- // => [['a', 'b'], ['c', 'd']]
- chunk(['a', 'b', 'c', 'd'], 3);
- // => [['a', 'b', 'c'], ['d']]
Browser Support for Spread in array literals
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 8.0 ✔ |
当前内容版权归 you-dont-need 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 you-dont-need .