-1

I want to pick an item from an array but randomly. The problem is that the indexes of the array are string. How can I select an item from this array but with a random index.

Nb: Indexes are string, I found answers with integer indexes but not string.

//................................................
const styles = StyleSheet.create({
  bigBlue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

//.......................................................

return (
  //if index was integer
  <Text style={styles[Math.floor(Math.random()*styles.length)]}>{this.props.text}</Text>
  // I need something like this : styles[RandomStringIndex()]
);
2
  • 2
    Please include code showing what you currently have Commented Sep 10, 2019 at 21:01
  • lenght well that would be one problem Commented Sep 10, 2019 at 21:17

1 Answer 1

1

It sounds like you want either Object.keys or Object.values.

Both of these convert an object's key:value mapping into a numbered array.

The Object.keys way:

var array_of_keys = Object.keys(styles);
var random_key = array_of_keys[Math.floor(Math.random()*array_of_keys.length)];
var random_value = styles[random_key];

The Object.values way:

var array_of_values = Object.values(styles);
var random_value = array_of_values[Math.floor(Math.random()*array_of_values.length)];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.