Created
January 30, 2018 18:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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