Javascript Array Find Function with example

    Oct 10, 2019       by Pankaj Kumar
javascript-find-function-example.jpg

Javascript has a rich set of inbuilt functions to work with string and arrays. Find() is also an inbuild function that returns a value of the first element in an array that satisfied the provided testing function. If there is no match in the array, undefined is returned.  

 

It is a pure function because it does not mutate the array on which it is called. Instead, it returns a value that satisfies the condition.

Following is the syntax of the array find() method.

arr.find(callback(element[, index[, array]])[, thisArg])

 

Parameters

callback: It is the function which execute on each value in the array, it takes 3 arguments

element: This is the current element in the array.

index(optional): The index of the current element in the array.

array(optional): The array on which find was applied.

thisArg(optional):  This is an Object to use as this inside callback.

 

Example:

 
const array1 = [7, 13, 9, 140, 54];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 13
 

 

  • For getting the index of the found element in the array, findIndex() is used.
  • For getting the index of value, Array.prototype.indexOf() is used.
  • For checking if a value exists in the array, Array.prototype.includes() is used.
  • For finding any element that satisfies the provided testing function, Array.prototype.some() is used.

Other Examples:

Following is an example to find an object in an array by one of its properties.

 

 
const inventory = [
{name: 'mangoes', quantity: 2},
{name: 'bananas', quantity: 12},
{name: 'oranges', quantity: 7}
];
 
function isMangoes(fruit) {
return fruit.name === 'mangoes';
}
 
console.log(inventory.find(isMangoes));
// { name: 'mangoes', quantity: 2 }
 

 

Achieving the same task using arrow function and destructuring

 

 
const inventory = [
  {name: 'mangoes', quantity: 2},
  {name: 'bananas', quantity: 12},
  {name: 'oranges', quantity: 7}
];
 
const result = inventory.find( ({ name }) => name === 'mangoes' );
 
console.log(result) // { name: 'mangoes', quantity: 2 }
 

 

Click here to find more details about this function.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!


WHAT'S NEW

Find other similar Articles here: