Lesson 7 of 10

Working With Data

Lesson 7: Array Methods

Learn how to use array methods like map and filter in Node.js. No browser needed.

Learning Goals

Example

// Save as lesson7.js
let prices = [8000, 12000, 25000, 6000];

let expensive = prices.filter(function (p) {
  return p >= 10000;
});

let withTax = prices.map(function (p) {
  return p * 1.18;
});

console.log(expensive); // [12000, 25000]
console.log(withTax);   // [9440, 14160, 29500, 7080]
Tip: Run node lesson7.js in your terminal to see the output.

When we write this, we mean:

Deeper Explanation

Array methods help you think in transformations instead of manual loops. In real projects, this makes your code easier to read and easier to test. Someone can quickly understand your intention: keep some values, modify some values, or pick one matching value.

The key beginner rule is this: every method has a job. Use the method that matches your intention. If you want fewer items, use filter. If you want changed items, use map. If you want one item, use find.

Common Beginner Mistakes

  1. Expecting filter to return one value instead of an array.
  2. Forgetting to return inside callback functions.
  3. Confusing map with forEach when a new array is needed.

Practice

  1. Use filter to keep scores above 50.
  2. Use map to add 5 marks to each score.
  3. Use find to get first score below 40.

Homework

Given product prices, create one list for cheap items and one list with VAT added.

Answer Guide
let productPrices = [3500, 9000, 12000, 5000];

let cheapItems = productPrices.filter(function (p) {
  return p <= 5000;
});

let pricesWithVat = productPrices.map(function (p) {
  return p * 1.18;
});

console.log(cheapItems);
console.log(pricesWithVat);
← Previous Lesson Next Lesson →