Question: I have a multi-dimensional array. I need some sort of loop to randomly pick a string in the array and check to see if that string contains a character. If it doesn't, then repeat until it finds one.

I wrote a for loop that checks the array for the string, BUT it starts from 0 and works its way through the array until it finds it. I need it randomly pick a string in the array...any help?

jsFiddle --> <http://jsfiddle.net/hz2MZ/1/>

jQuery

```
$(document).ready(function() {
var myarr = [{"Name":"Bob", "Char":"134"},
           {"Name":"Phil", "Char":"134"},
           {"Name":"Jane", "Char":"1"},
           {"Name":"Don", "Char":"4"},
           {"Name":"Dan", "Char":"2"},
           {"Name":"Jan", "Char":"12"},
           {"Name":"Bill", "Char":"24"},
           {"Name":"Sam", "Char":"14"},
           {"Name":"Jake", "Char":"23"},
           {"Name":"Ben", "Char":"3"}];

$('button').click(function() {
   for(var i = 0; i < myarr.length; i++) {
       if(myarr[i].Char.indexOf('2') !== -1) {
           alert("Name: " + myarr[i].Name + "\nChar: " + myarr[i].Char);
         return;
       } else {}
    } 
});

});

```

Answer: 
My solution

```
$('button').click(function () {
        var found = false;

        while (!found) {
            var randomIndex = Math.floor(Math.random() * myarr.length);
            if (myarr[randomIndex].Char.indexOf('2') !== -1) {
                alert("Name: " + myarr[randomIndex].Name + "\nChar: " + myarr[randomIndex].Char);
                found = true;
            } else {}

        }
    });

```

**edit**

Updated endless loop problem

```
$('button').click(function () {
    var found = false;
    var maxRandom = 20;
    var currentRandom = 0;

    while (!found && currentRandom < maxRandom) {
        var randomIndex = Math.floor((Math.random() * myarr.length));
        currentRandom++;

        if (myarr[randomIndex].Char.indexOf('2') !== -1) {
            alert("Name: " + myarr[randomIndex].Name + "\nChar: " + myarr[randomIndex].Char);
            found = true;
        } else {}
    }
}

```
One approach is to copy the array, then randomly splice one member from the copy and check for the required value:

```
function randomValueByChar(arr, c) {
  var a = arr.slice && arr.slice();
  var i = a.length || 0;
  var t;

  while (i--) {
    t = a.splice(Math.random() * i | 0, 1);
    if (t[0].Char.indexOf(c) != -1) return t;  
  }
}

```

Another approach is to create an array of the indexes (e.g. `[0,1,2,3…]`), then randomly splice one value at a time and use it as an index to retrieve a value from the array. Both approaches will not have an infinite loop and will visit each member a maximum of once.