Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Created January 30, 2018 18:57
Show Gist options
  • Save GreggSetzer/b38743a4ba34d00434e81804b9a607af to your computer and use it in GitHub Desktop.
Save GreggSetzer/b38743a4ba34d00434e81804b9a607af to your computer and use it in GitHub Desktop.
Javascript Interview Question: Chunked Array - Given an array, create a new array containing chunked arrays of the given size.
/*
Given an array and size, create a new array containing chunked elements with the size provided.
For example, given the array ['Alligator', 'Bear', 'Cat', 'Dog', 'Elephant', 'Flamingo', 'Giraffe'] and size 2,
return an array of arrays with 2 elements per array.
Result:
[["Alligator", "Black Bear"], ["Cat", "Dog"], ["Elephant", "Flamingo"], ["Giraffe"]]
*/
function chunk(arr, size) {
let chunkedArr = [];
let index = 0;
while (index < arr.length) {
chunkedArr.push(arr.slice(index, index + size));
index += size;
}
return chunkedArr;
}
//Try it
const animals = ['Alligator', 'Bear', 'Cat', 'Dog', 'Elephant', 'Flamingo', 'Giraffe'];
console.log(chunk(animals, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment