Reputation: 729
I've got json data.
[
["Mango","M"],
["Lychee","L"],
["Pineapple","P"],
["Banana","B"]
]
I need to be able to pick an Array item randomly (e.g. ["Pineapple","P"]
). How can I do a random pick?
var alphabetNum = "";
$.ajax (
{
url:"getalphabet.json"
}).done(function(data) {
alphabetNum = data;
});
Upvotes: 4
Views: 5621
Reputation: 386654
Just take Math.random()
and the length of the array as factor.
var array = [
["Mango","M"],
["Lychee","L"],
["Pineapple","P"],
["Banana","B"]
];
var randomItem = array[Math.random() * array.length | 0];
// take only the element with index 0
alert(randomItem[0]);
Upvotes: 7