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 trialDaniel Nitu
13,272 PointsWhy 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]]
}
]
};
Bruno Navarrete
Full Stack JavaScript Techdegree Graduate 22,246 PointsJonathan 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
4,884 PointsSince 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
3,851 PointsBecause without the 0 index, we would get back [[0, 0]] but we want just [0, 0]. Can someone confirm my answer?
Mohamad Fadhli Ismail
11,935 PointsMohamad Fadhli Ismail
11,935 PointsWould love if Guil Hernandez or Joseph Fraley can answer this. I am not entirely understand it myself.