8

Say I have a number 18, instead of an array, in hand.

What is the best way to create a functional loop in JS given a number X instead of array of X elements?

I can do this:

[1,2,3].forEach(function(){

));

but if I have the number 3

I can do

for(var i = 0; i < 3; i++){

}

but I want that loop to be functional instead

Alexander Mills
  • 78,517
  • 109
  • 412
  • 724
  • 2
    We have moved on past functional-style and are now using generators. Back to the `for` statement! –  May 18 '16 at 04:27
  • 1
    @torazaburo , i am not sure if he asked the same question as you have marked it duplicate for i think he just wants to iterate x number times without creating an array or using for loop. not sure maybe. – AJS May 18 '16 at 12:59
  • 1
    something like this [JSBIN](http://jsbin.com/jaxoyiweva/edit?js,console,output) – AJS May 18 '16 at 13:08
  • Iterating *n* times in a "functional way" is the same, for all practical purposes, as creating an array of n numbers and then using some iterating-type function like `map` or `forEach` on the result, so yes, I would say it is a duplicate. –  May 18 '16 at 13:58

3 Answers3

7

If you have a number and you want to create a loop then you can use the number in limiter condition in the for loop.

for(var i = 0; i < number; i++)

Edit 1: you can use foreach on arrays only, in that case since you have a number already you can create a array of that length and then use the foreach on it.

var foo = new Array(number).fill(0);

foo.foreach()

Also another option is

var N = 18;

Array.apply(null, {length: N}).map(Number.call, Number)

result [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]

Many more options available in this thread Create a JavaScript array containing 1...N

Community
  • 1
  • 1
Rajshekar Reddy
  • 18,019
  • 3
  • 36
  • 56
5

I don't understand why you want to do this. An equivalent to:

[1,2,3].forEach(function(){ ... ));

Is

var limit = n;
while (--limit) {(  // Note: 0 is falsy
    function(){ ... }
)(limit);}

Or if you really want to use an array structure, the following will do:

new Array(limit).fill(0).forEach(function(){...});

You might be interested in Myth of the Day: Functional Programmers Don't Use Loops.

luiscla27
  • 3,127
  • 26
  • 39
RobG
  • 134,457
  • 30
  • 163
  • 204
1

Per this question, you can "functionally" iterate over a linear sequence relatively easily using:

Array.apply(null, Array(number)).map(function () {}).forEach(...)

Not sure what advantage this gives you versus a regular for-loop with an index, though it is a neat trick.

Community
  • 1
  • 1
Matt
  • 3,597
  • 2
  • 25
  • 38