Skip to content

Commit 8950579

Browse files
author
Connor Leech
committed
add array chunking
1 parent 45392ba commit 8950579

File tree

1 file changed

+62
-1
lines changed

1 file changed

+62
-1
lines changed

udemy-interview-bootcamp-course/array_chunking.js

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,69 @@
99
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
1010

1111
function chunk(array, size) {
12+
let currentChunk = 0;
13+
let result = [];
14+
let chunk = [];
1215

16+
for(var i = 0; i < array.length; i++){
17+
if(currentChunk == size){
18+
result.push(chunk);
19+
currentChunk = 0;
20+
chunk = [];
21+
}
22+
23+
currentChunk++;
24+
chunk.push(array[i]);
25+
}
26+
27+
if(chunk.length) result.push(chunk);
28+
29+
return result;
30+
}
31+
32+
33+
function chunkSolution1(array, size){
34+
// create empty array to hold all other arrays
35+
const chunked = [];
36+
37+
for(let element of array){
38+
// retrieve the last element in the chunked array
39+
const last = chunked[chunked.length - 1];
40+
41+
// if there is no last element or it's length is the size
42+
if(!last || last.length === size){
43+
44+
// add a new chunk with the current element
45+
chunked.push([element]);
46+
} else {
47+
// add the current element into the chunk
48+
last.push(element);
49+
}
50+
}
51+
52+
return chunked;
1353
}
1454

1555

16-
console.log(chunk([1, 2, 3, 4], 2));
56+
// Rolling window with startIndex variable
57+
// Good practice for using Array.prototype.slice
58+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
59+
function chunkSolution2(array, size){
60+
let startIndex = 0;
61+
let output = [];
62+
63+
while(startIndex < array.length){
64+
65+
output.push(array.slice(startIndex, startIndex + size));
66+
67+
startIndex += size;
68+
}
69+
70+
return output;
71+
}
72+
73+
74+
75+
console.log(chunkSolution2([1, 2, 3, 4], 2));
76+
console.log(chunkSolution2([1, 2, 3, 4, 5, 6, 7, 8], 3));
77+
console.log(chunkSolution2([1, 2, 3, 4, 5], 4));

0 commit comments

Comments
 (0)