Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

find() vs filter() in JavaScript – Differences Explained with Examples

/* What is the filter() method?
	This method returns all the elements of the array that satisfy the condition
    specified in the callback function.
*/

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.
*/



/* What is the find() method?
	This method returns first element of the array that satisfies the condition
	specified in the callback function.
*/

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.
*/
 
PREVIOUS NEXT
Tagged: #JavaScript #Differences #Explained #Examples
ADD COMMENT
Topic
Name
6+8 =