Last active
December 20, 2020 00:12
-
-
Save neuralline/42a0957392b12c8b4fa859db099e9c53 to your computer and use it in GitHub Desktop.
ES6 break array Into n equal 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 of length >= 0, and a positive integer N, return the contents of the array divided into N equally sized arrays. | |
* Where the size of the original array cannot be divided equally by N, the final part should have a length equal to the remainder. | |
* | |
* #my solution | |
* it's modern, its pure function, uses ES6 method channing and also it returns brand new array with out modifying the original | |
* | |
* @param {[]} arr original array | |
* @param {number} divideBy number | |
* @returns {[]} | |
*/ | |
const breakArrayIntoChunks = (arr, divideBy) => { | |
return arr | |
.map((_, index) => | |
index % divideBy ? undefined : [...arr.slice(index, index + divideBy)]//slice the aray from i to n | |
) | |
.filter(chunk => chunk)//remove undefind content | |
} | |
/** | |
* | |
* test | |
*/ | |
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] | |
const n = 2 | |
console.log(breakArrayIntoChunks(array, n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment