0

I have an array:

arr = ["blue", "red", "green"];

How can I get a random element from the array except the element with value "red"?

I know I an use the following to get a random array element but how do I put a "where/if" statement?

1
  • 2
    Create another array without red element. Now the problem is well defined and easy to google for. Commented May 27, 2016 at 2:33

5 Answers 5

7

The code that is guaranteed to complete would look like this:

var arr = ["blue", "red", "green"];

var onlyValidValues = arr.filter(v => v !== 'red');

if (onlyValidValues.length === 0) {
    throw new Error('empty array');
}

var randomItem = onlyValidValues[Math.floor(Math.random() * onlyValidValues.length)];

So compared to other suggestions it only picks random values from an array cleaned from the "forbidden" elements.

Sign up to request clarification or add additional context in comments.

Comments

2

Use Math.random() within a while loop

var arr = ["blue", "red", "green"],
  val = 'red';

while (val == 'red')
  val = arr[Math.floor(Math.random() * arr.length)]

console.log(val);


Or copy the array and remove red from it, then get an element

var arr = ["blue", "red", "green"],
  arrNew = arr.slice(0); // copy the array
arrNew.splice(arr.indexOf('red'), 1); // remove red from it

val = arrNew[Math.floor(Math.random() * arrNew.length)] //get random element

console.log(val);


In case there is multiple red elements in array, then use filter() as in @zerkms answer.

5 Comments

This may never complete.
@zerkms I think cosmic rays causing the code to error is more likely
@2426021684 the standard does not put any constraints on the implementation of Math.random. So having Math.random = function() { return 0.42; } would still keep the engine implementation standard complaint.
@zerkms What kind of implementation hard codes Math.random?
@2426021684 It's a different question, I'm just saying what the standard requires and what it does not.
1

You could do something like this:

arr = ["blue", "red", "green"];

getRandomChoice = function(arr) {
    var choice = arr[Math.floor(Math.random()*arr.length)];
    while (choice === "red") {
        choice = arr[Math.floor(Math.random()*arr.length)];
    }
    return choice;
}

getRandomChoice(arr)

Comments

1

This may be useful..

var arr = ["blue", "red", "green"];
var item = arr[Math.floor(Math.random()*arr.length)];
while(item == "red"){
item = arr[Math.floor(Math.random()*arr.length)];

}
document.write(item)

Hope it helps to solve your problem

Comments

1

I've done a function using new ES6 features. With my function you can exclude more than one element. Here's my approach :

const arr = ["blue", "red", "green"];

function getRandomElementExcluding (...excluded){
  try {
    let random = Math.ceil(Math.random() * arr.length - 1);
    
    if(excluded === undefined)
      return arr[random];
    else if (excluded.includes(arr[random])) 
      return getRandomElementExcluding(...excluded);
    else 
      return arr[random];
  } catch (e){
    return false;
  }
}

console.log( getRandomElementExcluding('red') );
// console.log( getRandomElementExcluding('red', 'green', 'blue') ); It will return false;

2 Comments

@zerkms Math.floor(Math.random() * onlyValidValues.length) used in your answer will improve my function ?
it's okay. It happens!! haha =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.