Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  188] [ 3]  / answers: 1 / hits: 101640  / 13 Years ago, tue, january 10, 2012, 12:00:00

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

More From » jquery

 Answers
0

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.


[#88101] Tuesday, January 10, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jalyn

Total Points: 173
Total Questions: 96
Total Answers: 90

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;