Array/Lodash.chunk
_.chunk(array, [size=1])
source / npm package / lodash
Creates an array of elements split into groups the length of
size
. Ifarray
cant be split evenly, the final chunk will be the remaining elements
創建一個二維數組,元素被分組成若干個塊(chunk),塊也是數組,其的長度為指定 size 的值。如果數組不能被平均分塊,最後一個塊將包含所有剩下的元素。
Since
- 3.0.0
Arugments
array
(Array): The array to process.[size=1]
(number): The length of each chunk
Returns
- (Array): Returns the new array of chunks.
Example
online
_.chunk([a, b, c, d], 2);// => [[a, b], [c, d]] _.chunk([a, b, c, d], 3);// => [[a, b, c], [d]]
Source
/** * Creates an array of elements split into groups the length of `size`. * If `array` cant be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @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, guard) { if (guard ? isIterateeCall(array, size, guard) : size === undefined) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result;}
源碼里有第三個參數,將 array, size, guard 對應到 value, index, object,來檢測 value 是否以 index 的位置存在於 object 里,如果是的話,就將 size 設置為 1;這樣做的目的,我不太清楚,但是能保證每一個塊的長度一致,就像文檔注釋寫的那樣,啟用迭代為了作用於 _.map
類似的方法?
轉載請備註作者及來源
如對本文有任何異議,歡迎評論區留言討論
推薦閱讀:
※我是如何學習數學的
※泰勒級數——小無相功
※關於GTM⑨的抄書日記-11
※一般情形下平均值不等式的證明及應用
TAG:數學 |