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 JavaScript Unit Testing Behavior Driven Development with Mocha & Chai Writing Our First Test Suite - Part 2

I still don't understand how this works...

for (let i = 0; i < player.ships.length; i ++) {
        ship = player.ships[i];
        shipPresent = ship.locations.filter(function (actualCoordinate) {
            return (actualCoordinate[0] === coordinates[0]) && 
                (actualCoordinate[1] === coordinates[1]);
        })[0];

I don't understand the [0] after ship.locations.filter(...). I'm guessing it will check the first coordinates in the locations array? but then how are the tests with multiple coordinates working?

It has been more frustrating figuring out how the game works than how Mocha/Chai works...

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

The important thing here is that the locations are a pair of numbers for the horizontal and vertical positions. This means ship.locations is a multi-dimensional array of n by 2 where n is the size of the ship. So coordinates[0] and coordinates[1] refer to those two numbers for each location.

filter() is an array method that goes through the each item, or with a multi-dimensional array each row of the first dimension, then returns a new array with some of the items from the old array removed. filter() takes a function as an argument that will be called for each item. That function is passed the array item, and is expected to return true or false for whether the item should be included in the new array. (This is covered in the course JavaScript Array Iteration Methods)