2010-08-27 24 views
1

J'essaie de traverser le tableau imbriqué var et de sélectionner les éléments du tableau qui satisfont une seule condition. J'essaie de sélectionner tout le premier élément ("choice1, choice2 ...") d'un tableau interne seulement quand "selectedIndex" est trouvé dans "el". Par exemple: si "opt2" est sélectionné dans la liste déroulante, il ne faut PAS sélectionner les éléments "choice2" et "choice4" car il n'y a pas de '2' dans ce tableau, mais il devrait obtenir tous les autres (choice1, choice3, choice5). Cliquez sur here pour la démonstration. Merci beaucoup d'avance.Sélection d'éléments dans des tableaux imbriqués

var all_data = new Array(
    new Array("selection1", new Array(
     new Array("choice1", new Array('a', [1, 2, 3, 4]), new Array('b', [3, 4])), 
     new Array("choice2", new Array('a', [3, 4]), new Array('b', [1, 4]), new Array('c', [1, 3, 4])) 
    )), 
    new Array("selection2", new Array(
     new Array("choice3", new Array('a', [2, 4]), new Array('b', [1, 3, 4]), new Array('c', [3, 4])), 
     new Array("choice4", new Array('b', [1, 4]), new Array('c', [1, 3])), 
     new Array("choice5", new Array('b', [1, 2, 4]), new Array('c', [1, 2, 3, 4])) 
    )) 
); 

function arraySearch(arr, i) { 
    var result = []; 
    for (var i = 0; i < arr.length; i++) { 
    for (var j = 0; j < arr[i].length; j++) { 
     for (var k = 0; k < arr[i][j].length; k++) { 
      var el = arr[i][j][k]; 
      if (el instanceof Array) { 
       //alert(el); 
       //here i want to check if 'i' exists in each 'el' 
       //and if found, concat the element "choice1, choice2..." 
      } 
     } 
    } 
    } 
    return result; 
} 
function getChoices(){ 
    selected_method = document.form.method.selectedIndex; 
    var n = selected_method+1; 
    var elements = arraySearch(all_data, n); 
    //alert(elements); 
}  
    <select name="method" onchange="getChoices();"> 
     <option>opt1</option> 
     <option>opt2</option> 
     <option>opt3</option> 
     <option>opt4</option> 
    </select> 
+0

Vous pouvez enregistrer un peu de texte en remplaçant * new Array (...) * par * [...] *. Donc, ce serait plus comme * var all_data = [["selection1", [["choice1", ['a', [1,2,3,4]]]]] * –

Répondre

2

Utilisez la récursivité pour effectuer une boucle dans les tableaux imbriqués ou pour aplatir le groupe avant la recherche.

function recursiveArraySearch(arr, filter) { 
    var result = []; 
    for (var i = 0; i < arr.length; i++) { 
     var el = arr[i]; 
     if (el instanceof Array) result = result.concat(recursiveArraySearch(el, filter)); 
     else filter(el) && result.push(el); 
    } 
    return result; 
} 

// Using it: 
var elements = recursiveArraySearch(all_data, function (el) { return true; }); 
Questions connexes