Ad space (banner)
🟨JavaScript Lessons
Lesson 14 / 69

Advanced Array Methods (filter and reduce)

In this lesson you'll master array's .filter() and .reduce() so you can extract matching data and aggregate it in short, readable code. This is for people searching "JavaScript filter reduce usage" or "JavaScript array aggregation."

.filter(condition) builds a new array containing only the elements that match a condition. .reduce((accumulator, element) => { ... }, initialValue) is a slightly more advanced but extremely useful method for collapsing an entire array into a single value (like a sum). Compared to writing the processing one element at a time in a for loop, using these methods makes "what you're trying to do" show up directly in the code, keeping it readable.

The sample code extracts only the scores that are 70 or above from an array of test scores using .filter((s) => s >= 70), and calculates everyone's total with .reduce((sum, s) => sum + s, 0). The second argument to reduce (0 in this case) is the starting value for the accumulation — you'd use 0 for a sum, 1 for a product, and so on, depending on what you're calculating.

A common beginner stumbling block is the order and role of .reduce()'s callback function arguments. It's easy to mix up "the accumulated value so far" (first argument) with "the element currently being processed" (second argument) — at first, it's a good idea to log each step to the console one at a time to check how it behaves. Also remember: if you forget to specify an initial value, the array's first element gets treated as the initial value instead.

In real development, combining filter and reduce is a classic pattern for data aggregation — extracting only orders that meet certain criteria from an order history, or calculating the total price of items in a cart. It's a combination worth remembering, since it shows up constantly in real-world logic like data analysis and sales aggregation.

.filter() and .reduce() can also be chained together, so you can write filtering and aggregation in a single line, like scores.filter((s) => s >= 70).reduce((sum, s) => sum + s, 0).

Similar aggregation processing is often combined with .map() too, and it's very common in real work to write a whole data-processing pipeline as one flow: "extract data matching a condition, transform it into just the information you need, then finally sum it up."

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)