Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

jquery - Search multi-dimensional array 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 "]
...

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.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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


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.


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

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

Then do your lookups like this:

r_table.r4;

Again this assumes that there are no duplicate rn items.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...