Array Higher-Order Methods
Why Higher-Order Methods?
Imagine you have a box of 100 LEGO bricks. You want to: pick out only the red ones, then make each one twice as tall, then count the total height. You could write three separate for loops... or you could use higher-order array methods that do all this in a clean, readable chain.
These methods take a callback function as an argument — a small function that describes what to do with each item. The method handles the looping for you. The Big Three you'll use constantly:
.map()— transform every item → get a new array of results.filter()— keep only items that pass a test → get a shorter array.reduce()— combine all items into a single value
Map, Filter & Reduce — The Big Three
Finding Things — find, findIndex, some, every
Sometimes you don't want to transform or filter an entire array — you just want to find something or ask a question about the array.
.find(fn)— returns the first item that passes the test (orundefined).findIndex(fn)— returns the index of the first match (or-1).some(fn)— returnstrueif at least one item passes.every(fn)— returnstrueif all items pass.includes(value)— checks if a specific value exists (no callback needed)
Find, Some & Every
Sort & forEach
.sort() uses a sorting algorithm to sort an array in place (it changes the original!). By default, it converts everything to strings and sorts alphabetically — which means [10, 2, 1] sorts to [1, 10, 2]! To sort numbers correctly, you need a compare function.
.forEach() runs a function for each item but doesn't return anything. It's like for...of in method form. Use it when you want side effects (like logging) rather than a new array.
Sort & forEach
Quick check
Continue reading