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

Daniel Nitu
Daniel Nitu
13,272 Points

Why is 'shipPresent' defined with the [0] index?

I don't understand why the variable shipPresent is assigned the index 0.

for(var 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];

Also, when I try adding another ship to the 'ships' object, the function doesn't work anymore.

var player = {
            ships: [
                {
                    locations: [[2, 9]]
                },
                {
                    locations: [[3, 3]]
                }
            ]
        };
Mohamad Fadhli Ismail
Mohamad Fadhli Ismail
11,935 Points

Would love if Guil Hernandez or Joseph Fraley can answer this. I am not entirely understand it myself.

Bruno Navarrete
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bruno Navarrete
Full Stack JavaScript Techdegree Graduate 22,246 Points

Jonathan Case explained it pretty well down there and I used this comment to remind myself why, I hope it helps:

// .filter returns an array with the values that matched the conditions. 
// Since we're looking for either undefined (not in given position) or the coordinates of the found ship, it will return an array with only one value [0]

Regarding your more-than-one-ship issue, it would help if we get a look at your full code. I added up to three and mine still works, even when it looks just like yours.

2 Answers

Jonathan Case
Jonathan Case
4,884 Points

Since we are passing only one coordinate in to check against, there can only be one or zero matches in our filter function. We can return only the first element of the array, which can only be undefined or the coordinate that matches. Then we catch it if it is undefined, and return false, or we return the matched coordinate.

Roger Hwang
Roger Hwang
3,851 Points

Because without the 0 index, we would get back [[0, 0]] but we want just [0, 0]. Can someone confirm my answer?