Algorithm 202: Array Chunking in 3 Ways
NJOKU SAMSON EBERE
Posted on March 18, 2020
Welcome to yet another series on algorithm - Algorithm 202. We are going to focus on array manipulation.
In how many ways can you chunk an array?
chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 2)
/* [
[ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
[ 7, 8 ],
[ 9, 10 ],
[ 11, 12 ],
[ 13 ]
]
*/
chunkArray(["Aaran", "Aaren", "Aarez", "Aarman", "Aaron", "Aaron-James", "Aarron"], 3)
/* [
[ 'Aaran', 'Aaren', 'Aarez' ],
[ 'Aarman', 'Aaron', 'Aaron-James' ],
[ 'Aarron' ]
]
*/
We want to look at 3 ways to achieve this.
Prerequisite
To benefit from this article, you need to have basic understanding of javascript's array methods.
Let's Chunk an Array using:
- for...of..loop, push()
function chunkArray(arr, limiter) {
let finalArray = [];
let tempArray = [];
for (value of arr) {
if (tempArray.length < limiter) {
tempArray.push(value);
} else {
finalArray.push(tempArray);
tempArray = [];
tempArray.push(value);
}
}
finalArray.push(tempArray);
return finalArray;
}
- for...loop, push(), slice()
function chunkArray(arr, limiter) {
let finalArray = [];
for (let i = 0; i <= arr.length; i += limiter) {
finalArray.push(arr.slice(i, i + limiter));
}
return finalArray;
}
- for...loop, push(), splice(), if...statement
function chunkArray(arr, limiter) {
let finalArray = [];
let arrayLength = arr.length;
for (let i = 0; i <= arrayLength; i++) {
if (arr.length != 0) {
finalArray.push(arr.splice(0, limiter));
}
}
return finalArray;
}
Conclusion
There are many ways to solve problems programmatically. You can try this out with recursion or other looping construct. I will love to know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
Up Next: Algorithm 202: Array Merging Without Duplicates in 4 Ways
You can also follow and message me on social media platforms.
Thank You For Your Time.
Posted on March 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.