Get Random Value From Array

I do a lot of coding...A LOT... but most of it is very proprietary or relies upon client architecture. Every once in a while I manage to have a

2 years ago

Latest Post SPA's Brain by Tracy Parks

I do a lot of coding...A LOT... but most of it is very proprietary or relies upon client architecture. Every once in a while I manage to have a need for something that needs to be done over and over again and can be applied agnostically. Yesterday was one of those times and I thought I'd share. It's nothing amazing or ground breaking, but if it helps someone, then that just makes the world that much better - albeit to an infinitesimal degree.

So what I needed to do was look at an array of images and just grab one. It didn't matter which one, I just needed one out of the lot. Well, I made a short snippet of a function that checks the parameter arr and first checks to make sure it is an object - safety feature so it doesn't throw errors if improperly used - and then generates a random number between 0 and the length of (arr-1). This ensures that the number generated can easily correspond to any of the values in the array . It then returns the value of the entry the number generated matches. If the arr is not an object, it returns false.

function getRndObj(arr) {
    if (typeof arr === 'object') {
        var a = Math.floor(Math.random() * ((arr.length-1) - 0 + 1)) + 0;
        return arr[a];
    } else {
        return false;
    }
}

et voilá. Like I said, it isn't much, but it certainly helped me out.

Tracy Parks

Published 2 years ago