简体   繁体   中英

get random values up to 3 from array apart from a given value

I have the following:

import React, { Component } from 'react';

class City extends Component {
    constructor(props) {
        super(props);

        this.cities = ["london", 'dubai', "frankfurt", "paris", "belfast", "dublin", "johannesburg"];
        this.newCities = [];
    }

    goNext(e) {
        this.props.setBgColor(false);
        this.props.setVisibility(false, false, false, false, false);

        for(var i = 0; i < this.cities.length; i++) {
            if(e.target.dataset.city == this.props.bgImg) {
                this.props.setFinalPlay(true, false);
            }

            else {
                this.props.setFinalPlay(false, true);
            }
        }
    }

    render() {
        let cities = [];

        // cities = this.cities.map((c, i) => { 
        //  var temp = "bg-" + i;

        //  console.log(c);

        //  console.log(this.props.bgImg);

        //  console.log(temp ==  this.props.bgImg);

        //  if(c.length < 5 && (temp ==  this.props.bgImg)){
        //      return <p data-city={"bg-" + i} onClick={this.goNext.bind(this)} key={i}>{c}</p>
        //  }
        // });

        this.cities.forEach((city, i) => {
            console.log("bg-" + i);
            if("bg-" + i == this.props.bgImg) {
                console.log("bg-" + i);
                cities.push(<p data-city={"bg-" + i} onClick={this.goNext.bind(this)} key={i}>{city}</p>);
            }
            else {
                console.log('no');
            }
        })

        return(
            <div className="city">
                <div className={"action-question " + this.props.catBgColor}>
                    <h3>Which city do you think this is?</h3>
                </div>

                <div className={"action-answers " + this.props.catBgColor}>
                    {cities}
                </div>

            </div>
        );
    }
}   

export default City;        

"this.props.bgImg" can be any value from "bg-0 to bg-7".

The first check is: (to make sure that there is a match)

if("bg-" + i == this.props.bgImg) {

however, I need to get another 3 random values that don't match "this.props.bgImg" so that user will have 4 options to choose from. How can I limit the array output to 3 random values + the match condition?

At the moment {cities} is only returning one value

You'd probably have to iterate once to get the match, like you're already doing, then store that match and try random values until you have an array of four cities, including the match you found earlier.

Something like

let cities = [];
let added  = [];

this.cities.forEach((city, i) => {
  if("bg-" + i == this.props.bgImg) {
    cities.push(<p data-city={"bg-" + i} onClick={this.goNext.bind(this)} key={i}>{city}</p>);
    added.push(i);
  }
});

while (added.length < 3) {
  let rand = this.cities[Math.floor(Math.random() * this.cities.length)];
  if ( !( added.includes(rand) ) {
    let city = this.cities[rand];
    cities.push(<p data-city={"bg-" + rand} onClick={city.goNext.bind(city)} key={i}>{city}</p>);
    added.push(rand);
  }
}

This will give you three random elements out of the array. You can just drop the select element out of the array, get the grab the three random and then put it into the result for your four choices.

 Array.prototype.getRandom= function(num, cut){ var A= cut? this:this.slice(0); A.sort(function(){ return .5-Math.random(); }); return A.splice(0, num); } var a1= ['bg-1', 'bg-2', 'bg-3', 'bg-4', 'bg-5', 'bg-6', 'bg-7']; console.log(a1.getRandom(3)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM