Why waste time writing long for loops if you can use Instance methods. This will make our code shorter and will clearly state our intention. For loops will surely do the same but it would sometimes make our code ambiguous to read and harder to maintain.
I have segregated the methods into groups to make things easier to grasp. The first group will return one element when the condition is passed while the second group will return all instances.
You can find the sample codes thru this link.
Returns the first instance of the search result of the array.
This method returns the value of the first element that matches the testing condition.
In this example, we will look for a book that has the title ‘Understanding ECMAScript 6’ and will retrieve all the details included in this object.
If the condition is met then it will return an item, otherwise undefined is returned.
Let’s check this first example below.
There’s another way of writing this:
And here’s an even shorter version of it:
This method is essentially the same as the find method however, this time it returns the index of where the element was found.
And when nothing is found, it will return -1. Let’s see another example below.
Here, we have an array of cities and we’re looking for the index of ‘Keiv’.
Now, let’s try to pass a city name that is not in the array.
This method checks if an array contains the element you were searching for and returns true or false. It is a very simple but powerful method.
To do this, we can simply place .includes after calling the array, as such:
includes method also takes an index as the second parameter. It will then check for a value in the array starting from the provided index and returns a result. If the second parameter is greater than the index of where the item is located, it will return false.
Return all instances of the search result of the array that satisfies the testing function.
This method takes the array and returns a new array that only contains the elements that match the condition.
Let’s see the example below to understand this further.
In this example, we want to get all flowers under the ‘Shrubs’ category.
Another way is to define a callback function before using it.
find: will go through elements within the array, then returns the first value that makes it return true.
filter: will filter the element through the function, return all the values that satisfy the condition.
findIndex: will look for the item and return its index starting from where you want it to search.
includes: returns true if the array has the item you’re looking for, otherwise false.
Do you find this blog helpful? Don’t forget to leave some feedback in the comment section.