搜索多维数组JavaScript

搜索多维数组JavaScript

本文介绍了搜索多维数组JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组:

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

我该如何搜索对于这个数组中的项目,根据每个项目中的第一个条目(r1,r2,..)
数组是巨大的我正在寻找一个快速有效的方法从这个数组获得结果
我使用了JQuery函数,但它在我的数组中找不到任何东西,我用这种方式:

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 arrayI used the JQuery function jQuery.inArray but it couldn't find any thing in my array , I used it this way :

alert($.inArray(["r1","7up",61,"Albertsons"],selected_products))// it returns -1
alert($.inArray("r1",selected_products))//this also returns -1


推荐答案

如果你想要它快,你需要一个 for 循环,这样你就可以休息找到匹配时的循环。

If you want it to be fast, you'll want a for loop so that you can break the loop when the match is found.

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.

如果有多个,那么你可以使用 $。grep 如果你想要jQuery:

If there's more than one, then you could use $.grep if you want 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.

以类似的方式,你可以使用 Array.prototype.filter ,如果你仅支持现代JavaScript环境。

In a similar manner, you could use Array.prototype.filter, if you only support modern JavaScript environments.

var result = selected_products.filter(function(v,i) {
    return v[0] === 'r1';
});






另一个解决方案是创建一个对象键是 rn 项。这应该给你一个非常快速的查找表。


One other solution would be to create an object where the keys are the rn items. This should give you a very fast lookup table.

var r_table = {};
for( var i = 0, len = selected_products.length; i < len; i++ ) {
    r_table[selected_products[i][0]] = selected_products[i];
}

然后执行以下查找:

r_table.r4;

再次假设没有重复 rn 项目。

Again this assumes that there are no duplicate rn items.

这篇关于搜索多维数组JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:32