Answer below, but some tips first:
1) It's generally a bad idea to declare anything const in the global scope.
2) You don't need to declare unused parameters in Javascript; it's chill like that.
3) Just because JS is chill and usually doesn't fuss about semicolons doesn't mean you shouldn't use them.
4) The
Javascript MDN[
^] is the single best resource (imo) for learning JS and also referencing how pretty much anything works in JS.
4a) The reason you get undefined is because
forEach[
^]'s return value is defined as undefined.
You almost had it. Use a nested
find
instead of
forEach
.
forEach
is for doing something to each element of a collection, not for finding and returning an element of a collection :) With some cleaning up and the fixes:
let cruiseLines = [{
Liner: 'Royal Carribean',
shipName: ['Symphony of the Seas', 'Vision of the Seas']
},{
Liner: 'Disney Cruise Line',
shipName: ['Disney Magic', 'Disney Spinner', 'Disney Swan']
}];
let findShip = function (targetShip){
return cruiseLines.find(function (cruiseLine){
return cruiseLine.shipName.includes(targetShip);
});
};
let lookShip = findShip('Disney Spinner');
console.log(lookShip);
If you don't want the entire object and just the name back (not sure why you'd want this, but re-reading your question I'm not sure):
let cruiseLines = [{
Liner: 'Royal Carribean',
shipName: ['Symphony of the Seas', 'Vision of the Seas']
},{
Liner: 'Disney Cruise Line',
shipName: ['Disney Magic', 'Disney Spinner', 'Disney Swan']
}];
let findShip = function (targetShip){
let shipName;
cruiseLines.forEach(function (cruiseLine){
shipName = cruiseLine.shipName.find(function (ship){
return ship === targetShip;
});
});
return shipName;
};
let lookShip = findShip('Disney Spinner');
console.log(lookShip);
If the above is what you want I'd go for this approach instead since you only need to know if the name exists, not what it is (you're already searching with the name):
let cruiseLines = [{
Liner: 'Royal Carribean',
shipName: ['Symphony of the Seas', 'Vision of the Seas']
},{
Liner: 'Disney Cruise Line',
shipName: ['Disney Magic', 'Disney Spinner', 'Disney Swan']
}];
let findShip = function (targetShip){
for (let cruiseLine of cruiseLines)
if(cruiseLine.shipName.includes(targetShip))
return true;
return false;
};
let lookShip = findShip('Disney Spinner');
console.log(lookShip);