Last Updated: February 25, 2016
·
680
· padawin

Get a 1-dimension array of random elements from a 2-dimensions array

window.random = function(rows, nbToReturn) {
    // group all sub arrays in a flat array
    return [].concat.apply([], rows)
        // randomize
        .sort(function(){return 0.5 - Math.random()})
        // takes the nbToReturn first
        .splice(0, nbToReturn);
};

Use:

var a = [[1,2,3],[4,5,6],[7,8,9]];
console.log(random(a, 4));

displays:

[4, 5, 6, 1]

Link to gist: https://gist.github.com/padawin/4b40456e48591dea5aeb

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside