The question has been asked for many languages, yet not for javascript.
Ruby has the method Enumerable#each_cons
which look like that:
puts (0..5).each_cons(2).to_a
# [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
puts (0..5).each_cons(3).to_a
# [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
How could I have a similar method in javascript for Array
?
Here is a function that will do it (ES6+):
// functional approach
const eachCons = (array, num) => {
return Array.from({ length: array.length - num + 1 },
(_, i) => array.slice(i, i + num))
}
// prototype overriding approach
Array.prototype.eachCons = function(num) {
return Array.from({ length: this.length - num + 1 },
(_, i) => this.slice(i, i + num))
}
const array = [0,1,2,3,4,5]
const log = data => console.log(JSON.stringify(data))
log(eachCons(array, 2))
log(eachCons(array, 3))
log(array.eachCons(2))
log(array.eachCons(3))
You have to guess the length of the resulting array (n = length - num + 1
), and then you can take advantage of JavaScript's array.slice
To get the chunks you need, iterating n
times.