Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript: Challenge Rendering the Game Getter Methods Solution

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Does this filter method works, at all?

I have broken this code to simpler snippets and it looks like filter method from the solution doesn't work... Take a look at these two codes:

It looks that this first solution that Ashley showed us doesn't work. I get in console every element of array.

class Tokens {
    constructor ( dropped ) {
        this.dropped = dropped;
    }

    get unusedTokens(){
        return this.dropped.filter(token => !token.dropped);
    }
}

const drop = [ false, true, false, true, false, true ];
const newToken = new Tokens ( drop );

console.log ( newToken.unusedTokens );

And just to compare, I did a for loop to filter elements in array and it works!

class Tokens {

    constructor ( dropped ) {
        this.dropped = dropped;
    }

    get unusedTokens(){
        const newArray = [];
        console.log ( this.dropped.length );
        for ( let i = 0; i < this.dropped.length; i++ ) {
            if ( this.dropped[i] === false ) {
                newArray.push ( this.dropped[i] );
            }
        }
        return newArray;
    }   
}

const drop = [ false, true, false, true, false, true ];
const newToken = new Tokens ( drop );

console.log ( newToken.unusedTokens );

Why the first solution doesn't work?

1 Answer

Steven Parker
Steven Parker
231,271 Points

The code in the video is:

        return this.tokens.filter(token => !token.dropped);

It's intended to filter an array of Token objects, using their "dropped" property (and each Token only has one).

But the code above is different:

        return this.dropped.filter(token => !token.dropped);  //"dropped" instead of "tokens"

This is taking an array of boolean states named "dropped" and attempting to filter each one on it's own "dropped" property, which it does not have.

But your loop indexes the boolean array and tests each one directly, giving a different result.

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Now I see... I have lost a little. But now everything's clear. Thanks!