搜索数组的函数

时间:2010-08-29 18:11:14

标签: javascript jquery

如何在嵌套数组中搜索元素。以下是数组的样子

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]]]
]

如果'a'等于'2',则以下函数必须在'result'中返回“choice1”和“choice3”:

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

请帮忙。非常感谢提前。

2 个答案:

答案 0 :(得分:2)

类似

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]

答案 1 :(得分:0)

我不清楚你到底需要什么。

如果您想知道数组是否包含元素,请使用Array.indexOf