JavaScript Array Methods Beyond Map, Filter, and Reduce
Everyone knows map, filter, and reduce. Here are the array methods I reach for that do not get enough attention. Map, filter, and reduce get all the attention in JavaScript tutorials, but the Array prototype has dozens of methods that solve real problems. After years of writing JavaScript, I have settled on a set of methods I use daily that go beyond the familiar three. Flat and FlatMap The flat() method flattens nested arrays to a specified depth. Before this method, I used Array.prototype.concat.apply([], nested) which was unreadable. Now [1, [2, [3]]].flat(2) produces [1, 2, 3] . The default depth is 1, which handles the common case of arrays nested one level deep. flatMap() combines map and flat in one pass. It maps each element and flattens the result by one level. This is useful when your mapping function returns arrays but you want a single flat result. const sentences = ['hello world', 'foo bar']; const words = sentences.flatMap(s => s.split(' ')); // ['hello', 'world', 'foo', 'bar'] I use flatMap when processing data that occasionally produces zero or multiple outputs per input. Returning an empty array from the callback effectively…