Im learning Javascript and facing trouble with an exercise.
By using array.map() method (and .filter()method). I have to modify this array of object:
var cakes = [
{
name: "cake",
flavor: "vanilla",
status: "available"
},
{
name: "brownie",
flavor: "chocolate",
status: "available"
},
{
name: "pie",
flavor: "strawberry",
status: "available"
},
{
name: "muffin",
flavor: "pistachio",
status: "available"
},
{
name: "donut",
flavor: "chocolate",
status: "available"
},
];
The modification is to set the status of all chocolate cakes in sold out.
For now I've tried several hypothesis. The meaningful one for me, was to put an other iteration with a "for" to ask the method to iterate on the different cakes and modify the status if the flavor was chocolate, but I understand that it's not needed. the method is alreaydy doing it.
I came back to an easier way to do things :
var soldOut1=cakes.map(function(cake){
if(cake.flavor==="chocolate"){
return cake.status="sold out";
}
else{return cake;}
});
console.log(soldOut1);
This gave me the most successful result:
[
{ name: 'cake', flavor: 'vanilla', status: 'available' },
'sold out',
{ name: 'pie', flavor: 'strawberry', status: 'available' },
{ name: 'muffin', flavor: 'pistachio', status: 'available' },
'sold out'
]
But as you may see, and Im sure it's pretty logical, but I can't keep the other properties for brownie and donut cakes. Im trying to understand the .map() method's limit. So is it possible to do that kind of work with a .map() method exclusievely?