|
| 1 | +// --- Directions |
| 2 | +// Given an array and chunk size, divide the array into many subarrays |
| 3 | +// where each subarray is of length size |
| 4 | +// --- Examples |
| 5 | +// chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]] |
| 6 | +// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]] |
| 7 | +// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]] |
| 8 | +// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]] |
| 9 | +// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]] |
| 10 | + |
| 11 | +// Steps |
| 12 | +// Create empty array to hold chunks called 'chunked' |
| 13 | +// Loop through each element in the unchanked array |
| 14 | +// Retrieve the last element in the chunked |
| 15 | +// If element does not exist or the element length is equal to chunk size push e new chunk to the chunked array with the element |
| 16 | +// Else add the element into the chunk |
| 17 | + |
| 18 | + |
| 19 | +// Solution 1 |
| 20 | +// function chunk(array, size) { |
| 21 | +// let chunked = []; |
| 22 | +// for (let element of array) { |
| 23 | +// const last = chunked[chunked.length - 1] |
| 24 | +// if(!last || last.length === size) { |
| 25 | +// chunked.push([element]) |
| 26 | +// } else { |
| 27 | +// last.push(element); |
| 28 | +// } |
| 29 | +// } |
| 30 | +// return chunked; |
| 31 | +// } |
| 32 | + |
| 33 | + |
| 34 | +// Steps |
| 35 | +// Create an empty chunk array |
| 36 | +// Create 'index' starts at 0 |
| 37 | +// While index is less than array.length |
| 38 | +// Push a slice of length size from array into chunked |
| 39 | +// Add size to index |
| 40 | + |
| 41 | +// Solution 2 |
| 42 | +function chunk(array, size) { |
| 43 | + let chunked = []; |
| 44 | + let index = 0; |
| 45 | + for (let el of array) { |
| 46 | + if(index < array.length) { |
| 47 | + chunked.push(array.slice(index, index + size)) |
| 48 | + index = index + size; |
| 49 | + } |
| 50 | + } |
| 51 | + return chunked; |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +module.exports = chunk; |
0 commit comments