2

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 {}
    } 
});

});
7
  • 2
    Shuffle the array first and then iterate over it. Commented Jul 5, 2013 at 21:41
  • 2
    "I have a multi-dimensional array." No you don't. You have an array of objects. Commented Jul 5, 2013 at 21:43
  • @FelixKling: Your glance was better than mine, I think. Commented Jul 5, 2013 at 21:48
  • I think making a copy of the array and shuffling it (or shuffling the original if there's no need to retain a specific order) is the best plan because then you stop either when you find a match or when you've checked every item. Commented Jul 5, 2013 at 21:52
  • "that empty branch is absolutely irrelevant" - Exactly my point. It's needless clutter, both as part of a question here and in real-world programs. Commented Jul 5, 2013 at 21:53

2 Answers 2

3

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 {}
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Note that this will be an endless loop if the character searched for isn't in any of the array items.
"I see TJ beat me too it" No, you caught the essential bit I missed, +1. I'd remove the entirely pointless else {} though. :-)
@nnnnnn there are multiple ways of handling that. The OP can decide which is best. He asked for a random way to select something, not a 100% bullet proof solution. This is a step in the right direction.
@T.J.Crowder I only noticed a while later, that you missed the loop. Also left the else, as the OP might want to add stuff :)
You could set var maxRandom = myarr.length; then decrease it-- while(maxRandom>0) and at each step swap the last item with the randomly choosen one. Then it could check all existing fields.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.