If you’ve been programming for any amount of time, you would be familiar with arrays. They are the among the first data structures taught in most programming lectures/courses. For good reason too, because they are pretty easy to work with. But in case you work in JavaScript, using arrays can be made a whole lot simpler with the help of some useful higher order methods!
The reason that these are called Higher Order Methods is that they can accept/return another function. If this seems a tad bit confusing, then it’s important that you understand why functions are first class citizens in JavaScript. It is just a fancy way of saying that functions are just like any other type of data, which can be stored, accessed, passed as arguments and even returned from another method!
The following image does a pretty good job at describing what a higher order function is
Credit: @joelnet on twitter
A quick heads up. These higher order methods will require the usage of callbacks and they will be a lot easier to write, if you are familiar with the arrow syntax of ES6. In case you’re not, you can go through the following section to see what it is. Here’s a pretty basic example:
// normal function definition
function add(a, b) {
return (a + b)
}
// arrow syntax
const add = (a, b) => (a + b);
You can convert a normal function definition into its arrow syntax counterpart, using the following steps:
Remove the
function
keyword and replace it with eitherconst
orlet
orvar
. We can do this because functions are first-class objects in JavaScript. (Note: In case you want an anonymous function, just remove thefunction
keyword and move to step 2)Next, put an arrow symbol
=>
in front of the arguments’ list, to indicate that the code following it will be the body of the function.After this, you can type curly braces and write the function body as usual. But, if your function body has just 1 line (the return statement), you can skip the curly braces, skip the return keyword, and just type out the expression that needs to be returned!
For functions with no argument, just leave empty brackets before the
=>
symbol.
const alertMsg = () => alert("This is just an example!")
Lastly, if you are handling just 1 argument in the function, you can skip the parenthesis around it.
const squared = x => (x \*\* 2)
Now that you have brushed up on the arrow syntax, let’s begin to understand some higher order array methods!
- forEach(): Think of it as a less verbose implementation of a
for loop
. It invokes a function on each array element, and its syntax goes like this:
array.forEach((element, index) => {
// some operations on the element
// maybe you want to use the index of the element
});
In case you want to see a pretty contrived example, take a look at the following example.
- map() : If you’ve understood forEach(), then this is a piece of cake! It functions exactly like a forEach, but returns a new array unlike the forEach() method. The syntax is as follows:
const returnedArr = array.map((currentEle) => {
// some operation on currentEle
});
It’s slightly different to the forEach() method, but you should be able to use them interchangeably for most applications. In case you want to know about the differences, you can go through this article.
reduce() is especially useful whenever you need to compute a single value based on the data stored in an array. As the name suggests, this reduces an array into a single value, but can be a little tricky to use! The callback function that this method accepts, works on each element of the array in a way that reduces the array to a single value. The syntax is as follows:
const reducedVal = array.reduce(callback, initialVal);
Here, callback
needs to take 2 arguments. The first argument acts as an accumulator, whose value persists throughout the process. The second represents the current value of the array.
A simple example can be to find the sum of the array elements.
In the above example, the reduce()
method has a callback function called reducerCallback
(very creative, I know!). This callback needs to have 2 arguments, I called mine acc
and current
.
The basic idea is that the value in acc
is persisted each time the callback method is executed. This means that if the reducerCallback
is executed for the 2nd element of demo , then the values of the arguments acc
and current
are, 12 and 34 respectively. The callback then adds these two values and returns them. This returned value is now the new value stored in acc
So, for the 3rd callback execution, the values of acc
and current
are 46 and 54. You can see how the array’s values are being used to get to a single value.
But I also mentioned a second argument called initialVal
in the syntax. This is set as the initial value of the acc
variable. In case you do not specify any initialVal
argument, acc
will take the array element at the 0th index as its default initial value.
Here is an article that gives you a verbose explanation about the workings of the reduce()
method
4 Practices to Help You Understand array.reduce() | by bitfish | JavaScript In Plain English | Medium
bitfish ・ ・ 6 min read
Medium
The next method that is used often is filter(). It is very helpful if you want to extract a sub-array from a larger array, based on some common property. The syntax is as follows
const filteredArr = array.filter(callback);
Here callback
accepts an argument current
which results is a boolean value being returned. Based on the return value, the current
value is pushed to filteredArr
.
For example, suppose you want to separate the even numbers from a given array.
Here, the callback
function is anonymous and it accepts an argument that represents the current element of the demo
array. If the callback
returns true
then item
is pushed to the resultant array filteredArr
.
Here, for all the even numbers in demo
, our callback
returns a 0(zero), which is falsy in nature. Hence, all the even numbers are omitted from filteredArr
. On the other hand, all the odd numbers return 1(one) which is equivalent to true . This way, our demo
array has been filtered!
You can go through the following article to see some more examples.
Learn & Understand JavaScript’s Filter Function | by Brandon Morelli | codeburst
Brandon Morelli ・ ・ 4 min read
codeburst.io
Lastly, let’s understand a higher order method used most often. sort() is a method that doesn’t quite work like we assume it would!
You would imagine that the following code works by sorting the array in ascending order by default, right?
const demo = [100, 20, 89, 3, 17];
demo.sort();
But, it returns the array [100, 17, 20, 3, 89]
. “What? Why?”, I hear you say. Let’s understand why sort() has such a behavior.
sort() assumes that all the array elements are String
by default, and sorts the elements based on the UTF-16 code values, in case it is not passed any callback!
This is why 100 will come before 20. In order to sort an array in a more traditional way (i.e, as numbers) we will need to use a callback function as follows array.sort(callback)
The callback
needs to accept 2 arguments and return a numeric value indicating how these 2 arguments need to be stored in the sorted array.
Here is an example to sort an array of elements in ascending order:
If
callback(a, b)
returns less than 0,a
comes beforeb
.If
callback(a, b)
returns 0,a
andb
are left at their current index.If
callback(a, b)
returns greater than 0,b
comes beforea
Note that callback(a, b)
must always return the same value when given a specific pair of elements a
and b
as its two arguments.
Here a
and b
are the 2 consecutive elements of the demo
array, which are continuously compared in the callback
. Here, if you wanted to sort the array in descending order, all you need to do is change the callback
to the following.
In case you want to look at more examples of how to use the sort() method, you can go through the following article.
Demystifying the Mysteries of sort() in JavaScript | by Aphinya Dechalert | Mad Hash*Map* | Medium
Aphinya Dechalert ・ ・ 5 min read
Medium
All said and done, these methods are a sliver of all the higher-order array methods offered by JavaScript. Although these are the methods that you’ll use on a more regular basis, it is not a futile attempt to go through the rest of the methods!
In case you wish to learn more about any of these array methods, or if you want to learn some more higher order methods, I’d suggest that you go to the MDN Docs, as it provides a pretty thorough explanation of all the methods that JavaScript has to offer.
Top comments (0)