Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way of filling javascript array

I'm trying to find a better way to fill an array using JavaScript.

Currently I have a function that looks like this to generate a fixed size array of sample data. I need the sample data to be not the same (non-homogenous) and preferably pseudo-random.

function () {
    var arraySize = (1024 * 10) / 4;  // Get size for 10k buffer

    var testdata = new Uint32Array(arraySize);

    for (var i = 0; i < arraySize; i++) {
        testdata[i] = Math.random() * 0xFFFFFFFF;
    };

    //...
};

And it works, but I suspect it's not very idiomatic for JavaScript.

My broader concern is that for the tests I'm running, I'm going to need larger (and larger!) arrays so I'm concerned about saturating the system for an otherwise temporary object.

Is there a more efficient / idiomatic approach to filling an array?


1 Answers

Your method is fine and very understandable.

Maybe more idiomatic, or at least concise, approaches come with EcmaScript 6:

  • TypedArray.from:

    Uint32Array.from( {length: 1024 * 10 / 4 /* 10k buffer */}, function() {
        return Math.random() * 0xFFFFFFFF;
    })
    // Alternatively, with an arrow function as a one-liner:
    Uint32Array.from( {length: 2560 }, () => Math.random() * 0xFFFFFFFF );
    
  • An immediately-invoked generator expression (IIGE) to create an iterator on demand:

    new Uint32Array(function*() {
        var arraySize = (1024 * 10) / 4;  // Get size for 10k buffer
        for (var i=0; i<arraySize; i++)
            yield Math.random() * 0xFFFFFFFF;
    }());
    
like image 167
Bergi Avatar answered Nov 29 '25 06:11

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!