搜索多维数组 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/8809425/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search multi-dimensional array JavaScript
提问by Evan Lévesque
I have an array which looks like this :
我有一个看起来像这样的数组:
selected_products[0]=["r1","7up",61,"Albertsons"]
selected_products[1]=["r3", "Arrowhead",78,"Arrowhead "]
selected_products[2]=["r8", "Betty Crocker Cake Mix (Variety)",109,"Arrowhead "]
...
how can I search for an item in this array according to the first entry in each item (r1,r2,..) the array is huge I am looking for a fast an effective way to get results from this array I used the JQuery function jQuery.inArraybut it couldn't find any thing in my array , I used it this way :
如何根据每个项目中的第一个条目 (r1,r2,..) 在这个数组中搜索一个项目这个数组很大我正在寻找一种快速有效的方法来从这个数组中获取结果我使用了 JQuery 函数jQuery.inArray但它在我的数组中找不到任何东西,我是这样使用的:
alert($.inArray(["r1","7up",61,"Albertsons"],selected_products))// it returns -1
alert($.inArray("r1",selected_products))//this also returns -1
回答by
If you want it to be fast, you'll want a forloop so that you can break the loop when the match is found.
如果您希望它很快,您将需要一个for循环,以便在找到匹配项时可以中断循环。
var result;
for( var i = 0, len = selected_products.length; i < len; i++ ) {
    if( selected_products[i][0] === 'r1' ) {
        result = selected_products[i];
        break;
    }
}
Of course this assumes there's only one match.
当然,这假设只有一场比赛。
If there's more than one, then you could use $.grepif you want jQuery:
如果有多个,那么$.grep如果你想要 jQuery ,你可以使用:
var result = $.grep(selected_products, function(v,i) {
    return v[0] === 'r1';
});
This will give you a new Array that is a subset of the matched items.
这将为您提供一个新数组,它是匹配项的子集。
In a similar manner, you could use Array.prototype.filter, if you only support modern JavaScript environments.
以类似的方式,Array.prototype.filter如果您只支持现代 JavaScript 环境,则可以使用。
var result = selected_products.filter(function(v,i) {
    return v[0] === 'r1';
});
One other solution would be to create an object where the keys are the rnitems. This should give you a very fast lookup table.
另一种解决方案是创建一个对象,其中键是rn项目。这应该会给你一个非常快速的查找表。
var r_table = {};
for( var i = 0, len = selected_products.length; i < len; i++ ) {
    r_table[selected_products[i][0]] = selected_products[i];
}
Then do your lookups like this:
然后像这样进行查找:
r_table.r4;
Again this assumes that there are no duplicate rnitems.
这再次假设没有重复的rn项目。
回答by ajax333221
So you are trying to find the index of the matched result?, well that changes the things a little bit:
因此,您正在尝试查找匹配结果的索引?,这稍微改变了一些事情:
var index=-1;
for(var i = 0, len = selected_products.length; i < len; i++){
    if(selected_products[i][0] === "r1"){
        index = i;
        break;
    }
}
if(index > -1){
    alert(selected_products[index].join(","));//"r1,7up,61,Albertsons"
}
Note:This will return the first result matched, if you want to get an array containing a list of all indexes:
注意:如果您想获取包含所有索引列表的数组,这将返回第一个匹配的结果:
var results=[];
for(var i = 0, len = selected_products.length; i < len; i++){
    if(selected_products[i][0] === "r1"){
        results.push(i);
    }
}
You can then call (for example) the last 'r1' matched like this selected_products[results[results.length-1]].join(",");
然后您可以像这样调用(例如)最后一个匹配的“r1” selected_products[results[results.length-1]].join(",");
回答by bicycle
You might wanna consider not doing these things in Javascript but in a server sided language (PHP/Java/.NET). In this way you:
你可能想考虑不在 Javascript 中做这些事情,而是在服务器端语言 (PHP/Java/.NET) 中。通过这种方式,您:
- Won't have problems with browser incapabilities (Mostly IE errors)
 - Shorter Javascript code and therefore faster to load.
 - Your site also works with Javascript turned off.
 
- 不会有浏览器无法使用的问题(主要是 IE 错误)
 - 更短的 Javascript 代码,因此加载速度更快。
 - 您的网站也可以在关闭 Javascript 的情况下运行。
 
An example how to do this in PHP:
如何在 PHP 中执行此操作的示例:
<?php 
function search($array, $key, $value) 
{ 
    $results = array(); 
    if (is_array($array)) 
    { 
        if (isset($array[$key]) && $array[$key] == $value) 
            $results[] = $array; 
        foreach ($array as $subarray) 
            $results = array_merge($results, search($subarray, $key, $value)); 
    } 
    return $results; 
} 
?>
回答by Asle
Just to pick up @am not i am's great input. Here is a live example. He solved it. I just wanted to give an example that it works. Hope it helps. This puts the values found from the selected value in 2 input fields.
只是为了选择@am not 我是很棒的输入。这是一个活生生的例子。他解决了。我只是想举一个例子来证明它有效。希望能帮助到你。这将从所选值中找到的值放入 2 个输入字段。
http://jsfiddle.net/asle/ZZ78j/2/
http://jsfiddle.net/asle/ZZ78j/2/
$(document).ready(function () {
var liste = [];
liste[0] = ["First Name", "12345678", "[email protected]"];
liste[1] = ["Second Name", "20505050", "second.nametestdomain.no"];
liste[2] = ["", "", ""];
$("#selger").change(function () {
    var valg = ($(this).val());
    var telefon;
    var epost;
    for (var i = 0, len = liste.length; i < len; i++) {
        if (liste[i][0] === valg) {
            telefon = liste[i][1];
            epost = liste[i][2];
            $("#tel").val(telefon);
            $("#epost").val(epost);
            break;
        }
    }
});
});
回答by rahool
Try this,
尝试这个,
// returns the index of inner array, if val matches in any array
function findIn2dArray(arr_2d, val){
    var indexArr = $.map(arr_2d, function(arr, i) {
            if($.inArray(val, arr) != -1) {
                return 1;
            }
            return -1;
    });
    return indexArr.indexOf(1);
}
function test(){
    alert(findIn2dArray(selected_products, 'r8'));
}
回答by Ilya
You may create index object { r1: 1, r2: 2,..., < search key >: < element index >, ...} and use it for searching.
您可以创建索引对象 { r1: 1, r2: 2,..., < search key >: < element index >, ...} 并将其用于搜索。

