Transform, choose, total and search an array of orders. Each method calls your arrow once per item.
JavaScript · beginner · 7 min · 17 steps · free
const orders = [
{ item: 'tea', price: 3 },
{ item: 'cake', price: 5 },
{ item: 'coffee', price: 4 },
];
const prices = orders.map((o) => o.price);
const big = orders.filter((o) => o.price > 3);
const total = prices.reduce((sum, p) => sum + p, 0);
const cake = orders.find((o) => o.item === 'cake');
console.log(prices, big.length, total, cake.price);orders is created and points to a new Array: [an Object, an Object, an Object].map calls the arrow for each order and collects what it returns.map callback gets o = { item: 'cake', price: 5 } and returns 5.map callback gets o = { item: 'coffee', price: 4 } and returns 4.prices = [3, 5, 4]: one result per order, in the same order.filter keeps the orders whose arrow returns true. tea costs 3: not > 3, so it is left out.filter callback gets o = { item: 'cake', price: 5 } and returns true.filter callback gets o = { item: 'coffee', price: 4 } and returns true.filter callback has finished, so its variables are gone. The value it returned, [an Object, an Object], is stored in big.reduce carries a running total: it starts at 0 (the second argument), then adds each price.reduce callback gets sum = 3, p = 5 and returns 8.reduce callback gets sum = 8, p = 4 and returns 12.reduce callback has finished, so its variables are gone. The value it returned, 12, is stored in total.find callback gets o = { item: 'tea', price: 3 } and returns false.find stops at the first match and returns that order.find callback has finished, so its variables are gone. The value it returned, {item: "cake", price: 5}, is stored in cake.[ 3, 5, 4 ] 2 12 5.Answer: [2, 4, 6]
Answer: undefined
← Arrays and References · Objects →