When should I use `map`, `filter`, or `reduce` on an array?
Quick answer
Use map when each input item should produce a corresponding transformed item; use filter when you want to keep only items that pass a test; use reduce when you want to accumulate items into one result, such as a total. With [3, 7, 10], these produce [6, 14, 20], [7, 10], and 20, respectively. [S1] [S2] [S3]
The question, the details, the next step.
A practical checklist
Write down the shape you want back: a transformed list, a selected list, or one accumulated result.
Use
mapwhen each input should produce its corresponding transformed value.Use
filterwhen a test decides which original items to keep.Use
reducewhen a running accumulation produces the result you need.Try the operation on a small example and compare its output with the result you intended.
A few more useful answers
Does `filter` change the values of the items it keeps?
Can `reduce` return a number instead of an array?
Yes. In the example, the callback accumulates a sum and the initial value is 0, so the result is the number 20. [S3]
What if I need to select items and then transform them?
Treat those as two distinct goals: first keep items that pass a test with filter, then transform the selected items with map. Check that the intermediate selected list is what you intend before using it.
Sources
References used for this guide.
- [S1] Array.prototype.map() — JavaScript | MDN developer.mozilla.org · Checked
- [S2] Array.prototype.filter() — JavaScript | MDN developer.mozilla.org · Checked
- [S3] Array.prototype.reduce() — JavaScript | MDN developer.mozilla.org · Checked
