Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.
給予一個陣列 arr 和一個區塊大小 size。 一個區塊陣列包含著原始的元素在這個 arr 中,但是由每個長度大小的子陣列所組成。 如果長度 arr.length 不能被區塊大小整除,則最後一個子陣列的長度可以小於等於 size。
You may assume the array is the output of JSON.parse. In other words, it is valid JSON.
Please solve it without using lodash’s _.chunk function.
您可以假設該陣列是 JSON.parse 的結果,換句話師,他是一個有效的 JSON。 請不要使用 loads 的 _.chuck函式解決問題
Example 1:
Input: arr = [1,2,3,4,5], size = 1 Output: [[1],[2],[3],[4],[5]]
Example 2:
Input: arr = [1,9,6,3,2], size = 3 Output: [[1,9,6],[3,2]]
Example 3:
Input: arr = [8,5,3,2,6], size = 6 Output: [[8,5,3,2,6]]
Example 4:
Input: arr = [], size = 1 Output: []
solution:
建立一個名叫 chunk 的函式,分別放入 arr, size 進去,先假設如果 arr 的長度不足以滿足 size,
此時有種作法,將原本的 arr 放入到新的空陣列中,或是原本的 arr 沒有元素,則回傳空陣列 []。
接著宣告要將符合 size 長度的元素,運用 while 迴圈搭配 splice 進行分割 size 長度,
直到長度為 0,同時將該元素用 push 放到 list 陣列中,並回傳 list。
Code 1: BigO(n)
var chunk = function(arr, size) { if (arr.length < size) return arr.length ? [arr] : [] const res = [] while (arr.length) { res.push(arr.splice(0, size)) } return res; };
FlowChart:
Example 1
console.log(chunk([1,2,3,4,5], 1)) [ [ 1 ] ] [ [ 1 ], [ 2 ] ] [ [ 1 ], [ 2 ], [ 3 ] ] [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ] [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ] //Output: [[1],[2],[3],[4],[5]]
Example 2
console.log(chunk([1,2,3,4,5], 1)) console.log(chunk([1,9,6,3,2], 3)) [ [ 1, 9, 6 ] ] [ [ 1, 9, 6 ], [ 3, 2 ] ] //Output: [[1,9,6],[3,2]]
Example 3
console.log(chunk([8,5,3,2,6], 6)) [ [ 8, 5, 3, 2, 6 ] ] //Output: [[8,5,3,2,6]]
Example 4
console.log(chunk([], 1)) [] //Output: []
Code 2: BigO(n)
var chunk = function(arr, size) { let res = [] for (let i = 0; i < arr.length; i+= size) { res.push(arr.slice(i, i + size)) } return res; };