I'm studying Javascript and I have this example using filter...
I have an object called fruits like that...
let data = {
"fruits": [{
"id": 0,
"name": "plum",
"description": "A plum is a purple fruit.",
"image": "https://cdn.shopify.com/s/files/1/0610/2881/products/cherries.jpg?v=1446676415",
"price": 220
},
{
"id": 1,
"name": "Apple",
"description": "An apple is a sweet, edible fruit produced by an apple tree. Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/265px-Red_Apple.jpg",
"price": 35
},
{
"id": 2,
"name": "Banana",
"description": "A banana is an edible fruit – botanically a berry – produced by several kinds of large herbaceous flowering plants in the genus Musa. In some countries, bananas used for cooking may be called plantains, distinguishing them from dessert banana",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Bananas_white_background_DS.jpg/320px-Bananas_white_background_DS.jpg",
"price": 12
},
{
"id": 3,
"name": "Grapes",
"description": "A small bunched fruit used to make wine",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Table_grapes_on_white.jpg/320px-Table_grapes_on_white.jpg",
"weight": 0.1,
"price": 45
}...
I have a cart with the items of fruits.
cart = [0, 3, 4, 5, 3]
this is the part that I don't understand...
const getCostOf = id => (data.fruits.filter(item => item.id == id))[0].price
What are doing
[0].price
??? Why I have to get the element [0] if item is going to change every step...
If I have other function...
const getTotal = cart => {
let total = 0;
cart.map(item => total += getCostOf(item))
return total;
}
Why in getConstOf
The example is using [0].price and not [item].price?
getCostOfmethod will always return an array with 1 element assuming it's provided with a valid id. You can access an array index with[index_number], so0being always there it's safe to call it straight away. Thefiltermethod will always keep the items that returnstrue.fruitskey in order to make use of different Array.prototypes. for example start of withdata.fruitsThen you can do filter.. data.fruits.filter(item => item)