0

How can I search for an element within a nested array. Following is what the array looks like

arr = [
   ["choice1", ['a', [2, 4]], ['b', [1, 3, 4]], ['c', [3, 4]]],
   ["choice2", ['b', [1, 4]], ['c', [1, 3]]],
   ["choice3", ['b', [1, 2, 4]], ['c', [1, 2, 3, 4]]]
]

if 'a' is equal to '2' then the following function has to return "choice1" and "choice3" in the 'result':

function arraySearch(arr, a) {
   var result = [];
   for(var i = 0; i < arr.length; i++) {
      // compare each arr[i] with 'a' for the very first occurrence, and move the next array
      if(arr[i].search(a)){
         result.concat(arr[0]);   
      }
   }
   return result;
}

Please help. Many thanks in advance.

3
  • Where does "a" equals 2. Explain your inputs and outputs better as in the current form it's really vague. Commented Aug 29, 2010 at 18:18
  • "a" equals 2 actually comes from html <select> option. Please check this demo page: jsfiddle.net/dQgFj/5 Commented Aug 29, 2010 at 18:30
  • I'm pretty sure you're just reasking the same question you asked before with different words. Why not just edit the original question? Commented Aug 30, 2010 at 4:17

2 Answers 2

2

something like

arr = [
    ["choice1", ['a', [2, 4]], ['b', [1, 3, 4]], ['c', [3, 4]]],
    ["choice2", ['b', [1, 4]], ['c', [1, 3]]],
    ["choice3", ['b', [1, 2, 4]], ['c', [1, 2, 3, 4]]]
    ];

find = function(arr, a) {

    var found = [];
    var foundCurrent;

    // for each 'choice'
    for (var choice = 0; choice < arr.length; choice++) {
        foundCurrent = false;

        // look at each entry in the array that is arr[current][1]
        for (var entry = 1; entry < arr[choice].length; entry++) {
            // search these for the value
            if (arr[choice][entry][1].indexOf(a) != -1) {
                if (!foundCurrent) {
                    found[found.length] = arr[choice][0];
                }
                foundCurrent = true;
            }
        }
    }
    return found;
};


find(arr, 2);
>> [choice1, choice3]
Sign up to request clarification or add additional context in comments.

Comments

0

It's not clear to me exactly what you need.

If you want to know whether an array contains an element, use Array.indexOf.

1 Comment

Array.indexOf isn't IE supported (until IE9), but there is a jQuery utility jQuery.inArray() that is similar. api.jquery.com/jquery.inarray

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.