Reputation: 25
I have an array of objects called seasons of length 300, and I trying to search through a certain property "Date" and add it to an array if it has not been found before. So far I have
var day=[];
for (var i=1; i<300; i++) {
var found=false;
for (var j=0; j<day.length; j++) {
if (day[j]==seasons[i]["Date"]) {
found=true;
break;
}
if (!found) {
day[day.length]=seasons[i]["Date"];
}
}
}
I'm not too sure where this is going wrong, and would appreciate some help. Thanks
Upvotes: 1
Views: 61
Reputation: 26022
You break
out of the inner for-loop, so the if (!found)
block is never executed.
Just put it after the inner loop:
for (var i = 1; i < 300; i++) {
var found = false;
for (var j = 0; j < day.length; j++) {
if (day[j] == seasons[i]["Date"]) {
found = true;
break;
}
}
if (!found) {
day[day.length] = seasons[i]["Date"];
}
}
Or do it in the if-block:
for (var i = 1; i < 300; i++) {
for (var j = 0; j < day.length; j++) {
if (day[j] == seasons[i]["Date"]) {
day[day.length] = seasons[i]["Date"];
break;
}
}
}
I guess the latter solution is easier to understand.
Upvotes: 1