Created
January 12, 2021 17:47
-
-
Save ahamed/9b0e7f065e87e6889f264fb485f7ce27 to your computer and use it in GitHub Desktop.
Make a chunk of fixed size of a linear array.
This file contains hidden or 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
| /** | |
| * Create chunk using a fixed size. | |
| * | |
| * @author Sajeeb Ahamed | |
| * @see https://stackoverflow.com/a/61413202/4610740 | |
| */ | |
| // Add the chunk function into the array prototype. | |
| Array.prototype.chunk = function(size) { | |
| // Make a clone of the main array as the main array being untouched. | |
| let data = [...this]; | |
| let result = []; | |
| // Splice the array until it's not being empty. | |
| while(data.length) { | |
| result.push(data.splice(0, size)); | |
| } | |
| return result; | |
| } | |
| const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
| const chunked = arr.chunk(2); | |
| console.log(chunked); | |
| // Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment