-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()]
);
Xunita
  • 69
  • 11

1 Answers1

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)];
Brilliand
  • 13,404
  • 6
  • 46
  • 58