1
\$\begingroup\$

Ive written a script to loop through a couple of unparalleled arrays a loop within a loop, Now im trying to find out if using break is all that's needed to exit and then continue over again.

What eles can you see or know to improve this?

var arr_vals = ["74","f4e3","22","r31","17","hundernds"]; // could have 500+ items
var arr_items = ["r31","22","65","100"]; // could have 50 items
var c = arr_items.length;
var arr_vals_len = arr_vals.length;
 for ( var i = 0; i < c; i++ ) { 
 var xid = arr_items[i];
 for (var j = 0; j < arr_vals_len; j++ ){
 if(arr_vals[j] === xid){
 // match !
 break;
}
 }
seand
2,4651 gold badge20 silver badges29 bronze badges
asked Apr 23, 2012 at 20:55
\$\endgroup\$
2
  • \$\begingroup\$ break will break out of the inner loop but not the outer one, so it will continue with the next iteration of the outer loop. Is that what you're asking? Also, I think you mean var j rather than var r. \$\endgroup\$ Commented Apr 23, 2012 at 21:01
  • \$\begingroup\$ @seand yes that's right, and r is supposed to be j \$\endgroup\$ Commented Apr 23, 2012 at 21:04

1 Answer 1

1
\$\begingroup\$

Instead of iterating through the inner array multiple times, it might be faster to create a map for the inner array beforehand and then test for a match within the map. (I think this will only work if they're arrays of strings, though.)

var arr_vals = ["74","f4e3","22","r31","17","hundernds"]; // could have 500+ items
var arr_items = ["r31","22","65","100"]; // could have 50 items
var vals_len = arr_vals.length;
var items_len = arr_items.length;
var map_items = {};
for(var j = 0; j < items_len; ++j) {
 map_items[arr_items[j]] = 1;
}
for( var i = 0; i < vals_len; ++i) {
 if(map_items[arr_vals[i]]) {
 // match!
 }
}

Perf test

answered Apr 23, 2012 at 21:26
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.