Learning Goals
- Use
mapto transform values. - Use
filterto keep some values. - Use
findto get first matching value. - Explain clearly what each array method returns.
Working With Data
Learn how to use array methods like map and filter in Node.js. No browser needed.
map to transform values.filter to keep some values.find to get first matching value.// 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]
node lesson7.js in your terminal to see the output.When we write this, we mean:
filter keeps values that pass a test.map creates a new list with changed values.prices stays unchanged unless you overwrite it.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.
filter to return one value instead of an array.return inside callback functions.map with forEach when a new array is needed.filter to keep scores above 50.map to add 5 marks to each score.find to get first score below 40.Given product prices, create one list for cheap items and one list with VAT added.
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);