loadsh函數(shù)庫(kù)中的
/** * * 將數(shù)組(array)拆分成多個(gè) size 長(zhǎng)度的區(qū)塊,并將這些區(qū)塊組成一個(gè)新數(shù)組。 * 如果array 無法被分割成全部等長(zhǎng)的區(qū)塊,那么最后剩余的元素將組成一個(gè)區(qū)塊。 * * @param array 需要處理的數(shù)組 * @param size 每個(gè)數(shù)組區(qū)塊的長(zhǎng)度 * @returns {Array<Array<T>>} * @example * * chunk(['a', 'b', 'c'], 2) * // => [['a', 'b'], ['c']] * * chunk(['a', 'b', 'c','d'], 2) * // => [['a', 'b'], ['c','d']] */ const chunk = <T>(array: Array<T>, size = 1): Array<Array<T>> => { // 邊界檢測(cè) // 需要考慮塊長(zhǎng)度小于1和空數(shù)組 const length = array.length; if (!length || size < 1) return []; let index = 0; // 處理數(shù)組起始位 let resindex = 0; // 新數(shù)組起始位 const result = new Array<Array<T>>(Math.ceil(length / size)); while (index < length) { result[resindex++] = array.slice(index, (index += size)); // size 為步長(zhǎng)值 } return result; }; export default chunk; import chunk from "../src/chunk"; const arr = [1, 2, 3, 4, 5, 6]; const n = chunk(arr, 3); console.log(n); // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] const arrs = ["a", "b", "c"]; const n1 = chunk(arrs, 2); console.log(n1); // [ [ 'a', 'b' ], [ 'c' ] ] const arre = [] as Array<string>; const n2 = chunk(arre, 2); console.log(n2); // [] |
|