Arrays · Lesson 20 of 45
map, filter and find
Transform, filter and search lists without loops.
These are the most important tools in modern JavaScript; you'll see them in every React or Node codebase. Each takes a callback called for every item, and none of them change the original array.
| Method | Returns | Use it to |
|---|---|---|
| a new array, same length | transform every item |
| an array of items that pass | pick items |
| the first match (or | look for one thing |
| its index (or -1) | get the position |
|
| “is there any…?” |
|
| “are they all…?” |
const prices = [100, 250, 40, 80] const withTax = prices.map((p) => Math.round(p * 1.14)) const cheap = prices.filter((p) => p < 100) const firstBig = prices.find((p) => p > 200) const anyFree = prices.some((p) => p === 0) const allPositive = prices.every((p) => p > 0) console.log(withTax) console.log(cheap) console.log(firstBig, anyFree, allPositive)
[100, 250, 40, 80]
.filter(p => p < 100)
[40, 80]
.map(p => p * 2)
[80, 160]
You can chain them: each works on the result of the one before.
const users = [
{ name: "Ali", age: 17, active: true },
{ name: "Mona", age: 22, active: true },
{ name: "Omar", age: 30, active: false },
]
const names = users
.filter((u) => u.active && u.age >= 18)
.map((u) => u.name)
console.log(names)
console.log(users.find((u) => u.name === "Omar").age)What's the output?
const n = [1, 2, 3, 4] console.log(n.filter((x) => x % 2 === 0).map((x) => x * 10))
What will this code print?
Complete the code
Make big hold only numbers above 5.
const nums = [2, 8, 5, 11] const big = nums.((n) => n > 5)
Exercise
Print the names of the products under 100 only.
Expected output: ["Pen", "Mug"]
const products = [
{ name: "Pen", price: 15 },
{ name: "Bag", price: 350 },
{ name: "Mug", price: 90 },
]
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.