Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional approach to basic array construction

This is my code, acting upon myArray:

var myArray = [];
var i;

for(i = 0; i < 20; i += 1) {
   myArray.push(Math.random());
}

Is there a functional equivalent of the above that does without the dummy variable i?

Favorite answers:

  • while(myArray.push(Math.random()) < 20);
  • $.map(Array(20), Math.random);
  • for(var myArray = []; myArray.push(Math.random()) < 20;);
like image 614
Randomblue Avatar asked Oct 22 '25 01:10

Randomblue


2 Answers

Not in ES5, there's no real functional equivalent to it, as you have to have something which has an amount of 20 to apply map to...

var my20ElementArray = [0,1,2,3,4,5,6,7,8,9,10];
var myArray = my20ElementArray.map(Math.random);

You could create an xrange-like function what is in Python but that would just hide this "unused" variable inside a function.

like image 92
Aadaam Avatar answered Oct 23 '25 16:10

Aadaam


With JavaScript 1.7, you can use Array comprehensions for this task:

var myArray = [Math.random() for each (i in range(0, 20))];

However, with ES5.1 you can just use the Array constructor to generate an array of arbitrary length, and then map it to random numbers. Only drawback is that map() does not work with uninitialised values, so I first generate an Array of empty strings by using join and split:

var myArray = new Array(20).join(" ").split(" ").map(Math.random);

Ugly, but short. A maybe better (but less understandable) idea from Creating range in JavaScript - strange syntax:

var myArray = Array.apply(null, {length: 20}).map(Math.random);

Starting with @FelixKlings comment, one could also use this one-liner without the i loop variable:

for (var myArray=[]; myArray.push(Math.random()) < 20;);
// much better:
for (var myArray=[]; myArray.length < 20;) myArray.push(Math.random());
like image 43
Bergi Avatar answered Oct 23 '25 15:10

Bergi



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!