DEV Community

Samuel Rouse
Samuel Rouse

Posted on

JavaScript: Arrays are Everywhere

Arrays are the foundation of nearly all data. If you ever have two or more of something, there is a good chance you end up with an array. And because arrays are nearly universal, knowing how to manipulate them is one of the major skills you need no matter what is in those arrays. This is true across almost all development. Whether you are transforming, filtering, or checking data; array methods are where it's at.

I don't expect developers to remember every function and capability of the language or Web APIs, but I do expect that you can identify one or more ways to translate (map), eliminate (filter), and transform (reduce) arrays.

This series talks about the different array methods and how we might use them. I'm interested in which methods you'd like to read about or discuss, so let me know if there are any you'd like to cover specifically.

Methods

Let's look at some array prototype methods and see what they offer. The table presents the method signature, including details of the callback. It shows us the return type, whether the response contains a record for every input, and whether it will run the callback for each entry in the array.

Method Returns One-for-one Runs for All
.map((value, index, array) => *) Array Yes Yes
.filter((value, index, array) => Boolean) Array No Yes
.reduce((accumulator, value, index, array) => *, optionalInitial) * No Yes
.find((value, index, array) => Boolean) */undefined No No
.some((value, index, array) => Boolean) Boolean No No
.every((value, index, array) => Boolean) Boolean No No
.forEach((value, index, array) => undefined) undefined N/A Yes
.sort((value1, value2) => Math.sign) Array Yes More?
.flat(optionalDepth) Array No Yes
.flatMap((values, index, array) => *) Array No Yes

A Note on Performance

Performance isn't going to be the primary consideration in this work. We will sometimes touch on it, but for most common data sizes there aren't often meaningful performance impacts. In general, you should focus on readability and maintainability of the code until performance becomes a consideration. Working on a resource-limited device or with an extremely large dataset comes are somewhat unique constraints. Let me know if you are interested in talking more about performance, though!

Next Steps

We'll break down the individual array methods and discuss how we can use them in this series. There are common, creative, and "clever" ways to use these methods, and we'll try to cover some of the things you might want to avoid for readability and maintainability.

Top comments (0)