I did a quick search for my question in the forms and this post basically covers it all apart from one aspect. I am just looking some advice on the proposal of a solution.
Basically, I have a list of name-value pairs in an array of objects
[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}] etc etc
Say we have 100 of these and I want to search for 1, one way to do this (the accepted answer in the linked post) would be as below:
var data = [{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}];
for(var i=0;i<data.length;i++){
if(data[i]['name'] == 'name2'){
console.log('The value is: ' + data[i]['value']);
break;
}
}
My question is, what if I want to find two values? Is there a more efficient way to do this other than looping through the array again looking for the second value? Say for example we were wanting to search for name1 AND name2. I was thinking of something along the lines of:
var data = [{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}];
for(var i=0;i<data.length;i++){
var x = 0;
if(data[i]['name'] == 'name1' || data[i]['name'] == 'name2'){
if (data[i]['name'] == 'name1'){
console.log('The value for name 1 is: ' + data[i]['value']);
x++
}
if (data[i]['name'] == 'name2'){
console.log('The value for name 2 is: ' + data[i]['value']);
x++
}
if (x == 2)
{
break;
}
}
}
This way we would only be looping through the array once and still breaking when both are found. Does this seem the best way to do it or would there be a more efficient solution?