Array Methods (map, filter)
Array Methods (map, filter): .filter() Pipeline — Eliminates Even Numbers JavaScript array methods are like specialized stations on a factory assembly line: raw material enters,
.filter() Pipeline — Eliminates Even Numbers
JavaScript array methods are like specialized stations on a factory assembly line: raw material enters, each station does its job, processed product comes out. `map()` is the painting station — transforms each element, count stays the same. `filter()` is the quality control gate — rejects items that fail, count can decrease. `reduce()` is the packaging press — compresses all elements into one value. Why does this matter? In Java you can do the same with `Stream.map()`, `Stream.filter()`, `Stream.reduce()`. But in JavaScript these methods chain directly on the array: `testResults.filter(t => t.status === 'failed').map(t => t.name)` — get the names of failed tests in one line. Critical QA use cases: processing object arrays from API responses, filtering test data, making conditional selections from multiple locator results — all done with these methods.
Array map & filter Examples
const fruits = ['🍎', '🍏', '🍊', '🍍']; // 1. map() — transform each fruit into juice const juices = fruits.map(fruit => fruit + '🥤'); console.log(juices); // ['🍎🥤', '🍏🥤', '🍊🥤', '🍍🥤'] // 2. filter() — keep only apples const apples = fruits.filter(fruit => fruit === '🍎' || fruit === '🍏'); console.log(apples); // ['🍎', '🍏']
Micro Lab: JavaScript QA coding practice
Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.
🎬 The .map()/.filter() Chain: Why the Original Array Is Never Touched
testResults (Original)
New Array: passedTests
New Array: testNames
forEach + push (Mutation Risk)
`testResults` holds 3 test outcomes: Login (passed), Payment (failed), Signup (passed). We want to filter it and extract names.
`.filter(test => test.status === "passed")` runs. `testResults` is NEVER changed — filter copies the matching items into a BRAND NEW array.
Result: `passedTests` — a NEW, INDEPENDENT array containing only Login and Signup. `testResults` still stands intact with its original 3 elements.