Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting another value from array in javascript

Tags:

javascript

What is the best way in JavaScript given an array of ids:

var ids = ['ax6484', 'hx1789', 'qp0532'];

and a current id hx1789 to select another value at random that is not the current from the ids array?

like image 791
Justin Avatar asked Aug 31 '25 16:08

Justin


1 Answers

Get the index of the value, generate a random value, if the random is the index, use 1 less (depending on random generated)

var random = Math.floor(Math.random() * ids.length)
var valueIndex = ids.indexOf("hx1789");

if (random === valueIndex) {
    if (random === 0) {
        random = 1;
    } else {
        random = random - 1;
    }
}

var randomValue = ids[random];

Demo: http://jsfiddle.net/sxzayno7/

And yeah, test the array length, if it's 1 - probably don't want to do this! Thanks @ThomasStringer

if (ids.length > 1) { //do it! }

Or just filter out the value and pull against that:

var randomIndex = Math.floor(Math.random() * (ids.length - 1))
var random = ids.filter(function(id) {
    return id !== "hx1789";
})[randomIndex]
like image 50
tymeJV Avatar answered Sep 02 '25 05:09

tymeJV