Skip to content

Instantly share code, notes, and snippets.

@neuralline
Last active December 20, 2020 00:12
Show Gist options
  • Save neuralline/42a0957392b12c8b4fa859db099e9c53 to your computer and use it in GitHub Desktop.
Save neuralline/42a0957392b12c8b4fa859db099e9c53 to your computer and use it in GitHub Desktop.
ES6 break array Into n equal size
/**
*
* 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