1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@user10319 You may also replace day[day.length]=seasons[i]["Date"]; with day.push(seasons[i]["Date"]);, it's a bit smaller to write and easier to read :)

Your Answer

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.