I have the following JavaScript code:
var postcodes = [['BD1',8],['BD2',20],['BD7',30]];
var rangeColours = [['red',10],['black',20],['blue',30]];
var postcodeColours = [];
for(var i=0; i<postcodes.length; i++) {
var match = 0;
for(var x=0; x<rangeColours.length; x++) {
if(postcodes[i][1] <= rangeColours[x][1] && match == 0){
postcodeColours.push([postcodes[i][0],rangeColours[x][0]]);
match = 1;
}
}
}
The output of the code is: (which is fine by the way)
[BD1,red][BD2,black][BD7,blue]
I’d like to know if there’s a way to make the code more efficient especially with regard to reducing the wasteful look ups that occur in the second for loop? At the moment I’m using the “match” variable and setting it to 1 if the value of the postcodes array element is less than the value of the rangeColours array element to ensure the push doesn’t repeat for each postcodes array element, is there a more elegant way of doing this?
Many Thanks
If you really wanted to optimize lookups you could remove the redundant lookup of
postcodes[i]andrangeColours[x]within the loop body by stashing it in a localI’m unsure if this would have a noticeable performance impact though. It feels like a micro optimization.