Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Ruby's each_cons in JavaScript

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?

like image 387
Ulysse BN Avatar asked Mar 17 '26 05:03

Ulysse BN


2 Answers

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.

like image 135
Ulysse BN Avatar answered Mar 19 '26 18:03

Ulysse BN


You could take the length, build a new array and map the sliced array with Array.from and the build in mapper.

Number.prototype[Symbol.iterator] = function* () {
    for (var i = 0; i < this; i++) yield i;
};

Array.prototype.eachCons = function (n) {
    return Array.from({ length: this.length - n + 1}, (_, i) => this.slice(i, i + n));
}

console.log([...10].eachCons(2));
console.log([...10].eachCons(3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 40
Nina Scholz Avatar answered Mar 19 '26 18:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!