最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get random array element where value not equal - Stack Overflow

programmeradmin9浏览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?

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?

Share Improve this question edited May 27, 2016 at 2:57 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked May 27, 2016 at 2:30 Cyber JunkieCyber Junkie 7766 gold badges16 silver badges31 bronze badges 1
  • 2 Create another array without red element. Now the problem is well defined and easy to google for. – zerkms Commented May 27, 2016 at 2:33
Add a ment  | 

5 Answers 5

Reset to default 7

The code that is guaranteed to plete 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 pared to other suggestions it only picks random values from an array cleaned from the "forbidden" elements.

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.

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)

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

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;

发布评论

评论列表(0)

  1. 暂无评论