Useful ways to find and organize data in arrays
.filter() takes an array and tests if each item passes a condition. It produces a new array with each one that passes.
The test is usually in the form of a function. Like many methods here that involve tests, this can be done with:
- An anonymous function inside the method
- A pointer function inside the method
- Referencing an external function defined elsewhere
Examples of all three below:
In each case,
[25, 22, 21, 30].
It will be noted if other methods can accept these three ways of taking a function. But for brevity’s sake, I’ll use pointer functions for the example.
This takes all values in an array and manipulates them in some way. The changed data is then put into a new array.
.forEach() applies a function to each item in an array. Unlike
.map(), this doesn’t take the result and apply them to a new array. It’s better for taking action on array values that don’t need a modified version.
Checks if any item in an array passes a condition or test. If at least one value passes, it returns true; otherwise it returns false.
.some() but only returns true if all array items pass the condition.
Checks if an array includes one specific value. Different from
.some() since it’s not checking a condition. Our uses of
.some() before could therefore be replaced with
.includes() for something more elegant.
.reduce() is a very versatile and powerful tool for controlling data structures. The general structure of one as explained here is:
.reduce() runs through each item in the array and lets you control what happens in the iteration. The available arguments to use are:
accis the “accumulated value,” or the one that carries over from each item in the array. It’s starting value is set in
initialValue, and it can be used as a reference point or changed in different ways throughout the reduce.
valueis the value of the current item in the iteration.
indexis the current item’s index
arrayis the array being reduced
A simple example the article also lists is using it to get the sum of an array
0 is the default starting value for
acc. It can be any number, value, or object. If you’re iterating to add key/value pairs, for instance, you can set it to
You can also use it to return an array based on if items are even or not
Spread operators (
...) let you expand an array if it’s in a variable. It’s useful if you need each array item to be a separate argument, but the array is in a variable. Using the spread operator puts each item as a separate value or variable, not a single array.
- Useful for combining arrays
- Useful for cutting items from arrays without splicing
Bonus: You can use this to write a function to remove items from arrays.
You can also use the spread operator so functions can accept any number of extra arguments. Great for ones that have a flexible number of extra parameters