javascript - 搜索数组的函数

标签 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”,则以下函数必须在“结果”中返回“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;
}

请帮忙。非常感谢。

最佳答案

类似的东西

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]

关于javascript - 搜索数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3595960/

相关文章:

javascript - 星级评定 Rails 4 jquery ajax javascriptraty

javascript - 如何访问和设置iFrame元素?

javascript - jQuery(function($) 是做什么的,它属于谁?

php - SQL 错误或 PHP 错误在我的 ajax [object object] 中返回

javascript - 加载表单,div 内不执行任何操作

javascript - 使用 mapDispatchToProps 映射的操作不带参数

javascript - snapshot.val() 返回未定义,但它正确记录。 Node.js 火力基地

javascript - 在同一页面中同时使用 Prototype 和 jQuery 时出现问题

jquery - 如何让 CSS 媒体查询与 jQuery $(window).innerWidth() 一起工作?

jQuery 选择 : how to limit the number of selected values and provide an error message