Javascript Array Find Method (with Example)

In this post, we will know what is javascript array find method and how to use it, with examples.

So while working with javascript arrays, sometimes we end up in a situation where we need to find an element from an array that satisfies a condition provided in a test function.

In this situation, find() method of javascript arrays comes into play. We can use the array find() method to return the first value of an array that satisfies a test function.

Also Read :

How to Print in Javascript – 3 Ways with Example
JavaScript forEach()

JavaScript Array.find()

Example 

const arr = [1, 2, 3, 4, 5, 6];

function isGreater(num) {
    return num > 2;
}

let evenNum = arr.find(isGreater);

console.log(evenNum); //3

find() Syntax

Syntax of the Javascript Array find() method :

array.find(function(element, index, arr),thisValue)

Here arr is the array.

find() Parameters

Parameters which find() method takes are :

function() – function to evaluate array elements on the basis of a condition (Required).

element – current element of the array (Required).

arr – the array of the current element (Optional).

thisValue – to use object as this inside the function (Optional).

find() Return Value

Returns the first element that satisfies a condition provided in a test function.
If no element satisfies the condition then it will return undefined.

Example 1: Using find() method

const randomArray = [8, 34, 8, 9, 7, 11];

function age(element) {
  return element >= 10;
}

let firstAge = randomArray.find(age);
console.log(firstAge); // 34

// using arrow operator
let secondAge = randomArray.find((element) => element <= 10);
console.log(secondAge); // 9

Example 2: Using find() with Object elements;

const employees = [
  { name: "John", salary: 10000 },
  { name: "Martin", salary: 15000 },
  { name: "Donald", salary: 20000 },
  { name: "Boris", salary: 34000 },
];

function isHigh(employee) {
  return employee.salary >= 10000;
}

let firstSalary = employees.find(isHigh)
console.log(firstSalary); // { name: 'John', salary: 10000 }

// using arrow function and Destructuring
let secondSalary = employees.find(({ salary }) => salary >= 12000);

console.log(secondSalary); // { name: 'Martin', salary: 15000 }

Example 3: Using find() with String elements;

const employees = ["john", "martin", "boris", "miller"];

const result = employees.find(employee => employee.startsWith("m"));

console.log(result); // "martin"

So that was all about the javascript array find method. Hope you understood the concept of the array find() method. If you still have any queries left in your mind then you can freely ask in the comment section below.

Leave a Comment

Your email address will not be published. Required fields are marked *