Array Functions You Need to Know (pt. 1)

In this article, I would like to describe some old and new Javascript functions that manipulate arrays. I will try to give an appropriate example for every one of them and maybe something more. So buckle up.

Photo by Agence Olloweb on Unsplash

.filter()

If you ever wondered how to pick items from an array, that matches certain conditions, this function is what you should be using. .filter() takes two arguments, but we will focus only on the first one.

.find()

Function .find() is similar to .filter() with one exception. Instead of returning new array containing all items matching condition, it return only the first one it could find.

.indexOf()

This method is very useful, when you want to find an items index by its value and not by certain condition. It is important to know, that in case it does not find a value, it will return -1 instead false as expected. Let’s take a look at the example.

Do not use this never ever in your code

.findIndex()

Similar to .find(), this method behaves almost the same, but instead of returning the value matching the condition, it returns its index. So for many occasions it can replace indexOf method, or even it provide much more power.

.includes()

Before ES2016, if you wild like to find something in array you would probably use indexOf and checks if its output is greater that -1.

Conclusion

In this short article, I went through 5 Javascript array methods that were created in order to find some values in array. These might help you to make your code little more readable and hopefully also to avoid some bugs. Although it is important to say that these functions, especially one with a callbacks might be little less performant as its for loop equivalents.

Passionate Angular developer with wide knowledge of other frontend technologies

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store