Skip to content

Commit e2f29e2

Browse files
committed
Chunk Array
1 parent fa43e23 commit e2f29e2

File tree

4 files changed

+85
-0
lines changed

4 files changed

+85
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ Once inside, run the command below:
1717
8. Search and Replace
1818
9. Anagram
1919
10. Pig-latin
20+
11. Chunk Array

src/chunkArray/index.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// pick a solution and insert here to run the test.
2+
3+
function chunkArray(array, size) {
4+
if(array.length <= size){
5+
return [array]
6+
}
7+
return [array.slice(0,size), ...chunkArray(array.slice(size), size)]
8+
}
9+
10+
module.exports = chunkArray;

src/chunkArray/solutions.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// LOOPING THROUGH THE ARRAY
2+
3+
function chunkArray(array, size) {
4+
let result = []
5+
6+
for (value of array){
7+
8+
let lastArray = result[result.length -1 ]
9+
if(!lastArray || lastArray.length == size){
10+
result.push([value])
11+
}else{
12+
lastArray.push(value)
13+
}
14+
}
15+
16+
return result
17+
}
18+
19+
// LOOPING THROUGH THE NUMBER OF CHUNKS
20+
21+
function chunkArray(array, size) {
22+
let result = []
23+
24+
let arrayCopy = [...array]
25+
26+
while (arrayCopy.length > 0) {
27+
result.push(arrayCopy.splice(0, size))
28+
}
29+
30+
return result
31+
}
32+
33+
34+
// USING .SLICE()
35+
36+
function chunkArray(array, size) {
37+
let result = []
38+
39+
for (i = 0; i < array.length; i += size) {
40+
let chunk = array.slice(i, i + size)
41+
result.push(chunk)
42+
}
43+
44+
return result
45+
}
46+
47+
//RECURSION
48+
49+
function chunkArray(array, size) {
50+
if(array.length <= size){
51+
return [array]
52+
}
53+
return [array.slice(0,size), ...chunkArray(array.slice(size), size)]
54+
}
55+

src/chunkArray/test.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const chunkArray = require('./index');
2+
3+
test('chunkArray is a function', () => {
4+
expect(typeof chunkArray).toEqual('function');
5+
});
6+
7+
test('Chunks array of 10 elements in twos', () => {
8+
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
9+
const chunkedArray = chunkArray(arr, 2);
10+
11+
expect(chunkedArray).toEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]);
12+
});
13+
14+
test('Chunks array of 13 elements in five and some', () => {
15+
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
16+
const chunkedArray = chunkArray(arr, 5);
17+
18+
expect(chunkedArray).toEqual([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]);
19+
});

0 commit comments

Comments
 (0)