Filter and Find in JavaScript – When should I use it?

Tram Ho

When you learn to ES6, the use of Filter and Find more often, but when to use filters and when to use Find, in this article, we will look at some examples, hopefully through these This example we will understand more and can improve your own performance code.

When you are learning about Filter and find, you should also understand through map, filter, reduce in javascript. It is also one of the methods that almost every developer must understand, because it helps and appears a lot in each of our applications.

Many of you here when you hear the title is pouting in different ways, which is “Oh, this is a long time ago”, or “Oạch, this is easy …”. Ha ha, you’re not wrong, but maybe you went through the examples below, are there any instances where you’re using it the wrong way? When you should have used Find in javascript and you used Filter ???

Find in JavaScript

Example 1


Filtering in JavaScript

Example 2


In the two examples above on the same data but the return of filter and find different. Look closely at it as [“maple”] and “maple”. Slowly, let’s move on to another example

Differences between Find and Filter in JavaScript

Example 3: Using Filter


Use Find


The two results show us that Find will return an element as soon as it becomes available (el> 0). In contrast, when using filter in ES6, it will return an Array that satisfies the condition. This means that the filter will loop through all elements in const jsonarr, and return an array containing all the elements that satisfy the condition (el> 0);

From example 3 we can know when to use Find and when to use Filter, not to be confused and then slow down your own code.

Using filters in JavaScript

Here, we will talk more about filters in ES6, why. Because filters will be used more in javascript programming, so the filter is more talked about than find by the devjs.

Javascript filter syntax

Where: newArray is an array to be returned

array is the original array used to filter

callback to process each element of the array

In callback yes

element is the current element being processed

The index doesn’t say much about the index

array is the original array

For example :

Share the news now

Source : Viblo