find() vs filter() Method in JavaScript – Differences

Differences in find & filter Method #JS

A common interview question that JavaScript developers often get asked is to explain the difference between the find() and filter() methods.

find() vs filter() Method in JavaScript - lookandlearnbd

What is filter() method ?

This method returns all the elements of the array that satisfy the condition specified in the callback function.
Let's see with an example how it actually works :

copy
     const x = [1, 2, 3, 4, 5];

     const y = x.filter(el => el*2 === 2);
        
     console.log("y is: ", y); // y is: [1]

If you check out the output of the above example, the value of y is an array of 1 element that satisfies the condition. This is because the filter() method iterates over all elements of the array and then returns a filtered array which satisfy the condition specified.

In Detail Description

filter() calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a value that coerces to true. Array elements which do not pass the callbackFn test are skipped, and are not included in the new array.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. callbackFn is invoked with 3 arguments.

  • the value of the element
  • the index of the element
  • the Array object being traversed
If a thisArg parameter is provided to filter, it will be used as the callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callbackFn is determined according to the usual rules for determining the this seen by a function.

The filter() method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array (with some filtered out).

The range of elements processed by filter() is set before the first invocation of callbackFn. Elements which are assigned to indexes already visited, or to indexes outside the range, will not be visited by callbackFn. If existing elements of the array are deleted in the same way they will not be visited.

What is find() method ?

This method returns first element of the array that satisfies the condition specified in the callback function. Let's see with an example how it actually works:

copy
     const x = [1, 2, 3, 4, 5];

    const y = x.find(el => el*2 === 2);
        
    console.log("y is: ", y); // y is: 1

Now, if you see the output of the above example, the value of y is 1. This is because the find() method searches for first element in the array that satisfies the condition specified. The main differences between above examples is:

  • filter() returns an array containing the element that satisfies the condition, but find() returns the element itself that satisfies the condition.
  • In filter(), whole array is iterated despite the fact that the element being searched for is present at the beginning. But in find(), as soon as the element that satisfies the condition is found, it gets returned.

In Detail Description

The find method executes the callbackFn function once for each index of the array until the callbackFn returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns undefined.

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

If a thisArg parameter is provided to find, it will be used as this value inside each invocation of the callbackFn. If it is not provided, then undefined is used.

The find method does not mutate the array on which it is called, but the function provided to callbackFn can. If so, the elements processed by find are set before the first invocation of callbackFn.

  • If an existing, yet-unvisited element of the array is changed by callbackFn, its value passed to the callbackFn will be the value at the time find visits that element's index.
  • Elements which are assigned to indexes already visited, or to indexes outside the range, will not be visited by callbackFn.
  • callbackFn will not visit any elements added to the array after the call to find begins.
  • Elements that are deleted are still visited.

Use Cases for find() & filter()

When you have a use case where more than 1 element is expected to be returned and you want to perform operation on all elements, then you can use the filter() method. But if you expect only a single element to be returned from the array, then you can use find() method and avoid extra iterations.
Let's look at examples of both use cases:

filter() - example

copy
     const x = [1, 2, 3, 4, 5];

        const y = x.filter(el => el%2 === 0);
        
        console.log("y is: ", y); // y is: [2, 4]

In above example, filter() makes more sense as you would want to iterate over all elements of the array to find the elements that are divisible by 2.

find() - example

copy
     const emp = [
        {
            name: "Ram",
            empID: 101
        },
        {
            name: "Sham",
            empID: 102
        },
        {
            name: "Mohan",
            empID: 103
        }
    ];
    
    const res = emp.find(el => el.empID === 102);
    
    console.log("res is: ", res); // res is: {name: 'Sham', empID: 102}

In above example, find() makes more sense as there is just 1 employee who has 102 as the empID so, find() helps to avoid iterating over the 3rd object in the array.


Thank you for reading!

You might also like to read

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.