map, filter, reduce and find

Transform, choose, total and search an array of orders. Each method calls your arrow once per item.

JavaScript · beginner · 7 min · 17 steps · free

What you'll learn

ArrayMethods.js

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);

Step by step

  1. orders is created and points to a new Array: [an Object, an Object, an Object].
  2. map calls the arrow for each order and collects what it returns.
  3. map callback gets o = { item: 'cake', price: 5 } and returns 5.
  4. map callback gets o = { item: 'coffee', price: 4 } and returns 4.
  5. prices = [3, 5, 4]: one result per order, in the same order.
  6. filter keeps the orders whose arrow returns true. tea costs 3: not > 3, so it is left out.
  7. filter callback gets o = { item: 'cake', price: 5 } and returns true.
  8. filter callback gets o = { item: 'coffee', price: 4 } and returns true.
  9. filter callback has finished, so its variables are gone. The value it returned, [an Object, an Object], is stored in big.
  10. reduce carries a running total: it starts at 0 (the second argument), then adds each price.
  11. reduce callback gets sum = 3, p = 5 and returns 8.
  12. reduce callback gets sum = 8, p = 4 and returns 12.
  13. reduce callback has finished, so its variables are gone. The value it returned, 12, is stored in total.
  14. find callback gets o = { item: 'tea', price: 3 } and returns false.
  15. find stops at the first match and returns that order.
  16. find callback has finished, so its variables are gone. The value it returned, {item: "cake", price: 5}, is stored in cake.
  17. It prints [ 3, 5, 4 ] 2 12 5.

Common mistakes

Best practices

Key takeaways

Check yourself

[1, 2, 3].map(x => x * 2)?

Answer: [2, 4, 6]

find with no match returns?

Answer: undefined

·

More in Objects and Arrays