js实现 chunk 函数分组数组
2023-09-14 09:07:43 时间
// 自己实现
function chunk(list, size) { let len = list.length; if (size < 1 || !len) { return []; } if (size > len) { return [list]; } // 最终返回数组 let res = []; // 向下取整 let integer = Math.floor(len / size); // 取余 let rest = len % size; for (let i = 1; i <= integer; i++) { res.push(list.splice(0, size)); } if (rest) { res.push(list.splice(0, rest)); } return res; } // console.log(chunk([1, 2, 3, 4, 5], 0)); console.log(chunk([1, 2, 3, 4, 5], -1)); console.log(chunk([1, 2, 3, 4, 5], 2)); console.log(chunk([1, 2, 3, 4, 5], 3)); console.log(chunk([1, 2, 3, 4, 5], 4)); console.log(chunk([1, 2, 3, 4, 5], 5)); console.log(chunk([1, 2, 3, 4, 5], 6)); // [] // [] // [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] // [ [ 1, 2, 3 ], [ 4, 5 ] ] // [ [ 1, 2, 3, 4 ], [ 5 ] ] // [ [ 1, 2, 3, 4, 5 ] ] // [ [ 1, 2, 3, 4, 5 ] ]
lodash chunk源码(供参考):https://github.com/lodash/lodash/blob/master/chunk.js
import slice from './slice.js' import toInteger from './toInteger.js' /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @returns {Array} Returns the new array of chunks. * @example * * chunk(['a', 'b', 'c', 'd'], 2) * // => [['a', 'b'], ['c', 'd']] * * chunk(['a', 'b', 'c', 'd'], 3) * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size = 1) { size = Math.max(toInteger(size), 0) const length = array == null ? 0 : array.length if (!length || size < 1) { return [] } let index = 0 let resIndex = 0 const result = new Array(Math.ceil(length / size)) while (index < length) { result[resIndex++] = slice(array, index, (index += size)) } return result } export default chunk
相关文章
- js 实现扁平数组转为树形结构数组及树形结构数组转为扁平数组
- js判断元素在不在数组中_js判断数组是否为空
- js数组排序—自定义快速排序
- js数组截取方式splice()和slice()方法
- 初识js中的闭包_Js闭包中变量理解
- 【说站】js中reduce在数组的使用
- JS对象转数组_js怎么把数组转成对象
- JS获取当前年份_js获取当前时间年月日
- 为了实现客服系统关键词分隔符切分,封装js实现根据多个分隔符分隔字符串为数组
- 笔记 | 一道使用js合并数组的题目
- JS实现新提醒标题闪烁 新提醒详解编程语言
- 使用JS连接MySQL数据库:实现化繁为简(js连接mysql数据库)
- JS技术连接Oracle数据库实现数据交互(js连接oracle实例)
- JS获取dom对象ajax操作读写cookie函数
- JS在数组插入字符的实现代码(可参考JavaScriptsplice()方法)
- asp.net通过js实现Cookie创建以及清除Cookie数组的代码
- 如何写JS数组sort的比较函数
- 远离JS灾难css灾难之js私有函数和css选择器作为容器
- JS随即打乱数组实现代码
- JS解析json数据并将json字符串转化为数组的实现方法
- js+数组实现网页上显示时间/星期几的实用方法
- Js获取数组最大和最小值示例代码
- js数组转json并在后台对其解析具体实现
- js数组去重的常用方法总结
- js获得当前时区夏令时发生和终止的时间代码
- js语法学习之判断一个对象是否为数组
- node.js中的path.join方法使用说明