Array Methods
JavaScript's array methods are becoming increasingly utilized in production, with many developers preferring them over the standard for
loop.
The most common array methods include: forEach
, map
, filter
, reduce
, find
, some
, every
, includes
.
You can find a full list on MDN.
You likely won't be forced to use them in an interview, and often it may even be easier to display logic using a standard for
loop (as I do in this course).
However, being able to integrate them into a solution can show you have command over the language and understand effective patterns.
Benefits of array methods include:
- Succinct syntax
- Declarative behavior
- Enforce immutability
- Minimize risk of side-effect behavior
- Explicit intent (array methods have a specific purpose which provides someone reading your code more context)
Below you will be given different for
loop code blocks, and it is your job to refactor them to use an array method.
Two methods will not be used:
forEach
: it is more of a catch-all method that has many usesreduce
: this is more complex and also can be used for different intents
Question 1
Solution 1
This is a perfect opportunity to use the map
function.
map
is used when we want to perform the same transformation on every item in an array.
In this case, we multiply everything by 2.
You can recognize needing a map function if you see a for
loop that makes a change to every i
item.
The map
method returns a new array with the updated items.
Question 2
Solution 2
The filter
method is used to remove items that don't match a condition specified by the callback function.
If the callback returns true
, the item is added to the output array.
If the callback returns false
, an item is not included.
A good candidate for filter
is when you use an if
inside of a for
loop to conditionally include items in your results.
Question 3
Solution 3
The includes
method will return true
or false
if an item exists in an array.
Question 4
Solution 4
The find
method will return the first item that matches a condition in the callback.
If no items match, it will return undefined
.
Question 5
Solution 5
The every
method will return true
if all items match a condition.
If at least one doesn't match, it will return false
.
Question 6
Solution 6
The some
method will return true
if at least one item matches a condition.
If none match, it will return false
.