AppDividend
Latest Code Tutorials

Javascript Array Find Example | Javascript Array Search

1

Javascript find() method returns a value of the first element in an array that satisfies a provided testing function. Otherwise, undefined will be returned. Javascript find method returns the value of the first element in an array that passes a test of provided function.

If Javascript array find() method finds an item where the function returns a true value, then Javascript find() returns the value of that array item immediately and do not check the remaining values of that array.

Javascript Array Find | Javascript find

Content Overview

Javascript Array.find() is the inbuilt function in JavaScript, which is used to get a value of the first item in the array that meets the provided condition.

If you need an index of the found item in the array, use the findIndex().

If you need to find an index of the value, use Array.prototype.indexOf().

It’s similar to findIndex(), but checks each item for equality with the value instead of using the testing function.

If you need to find if the value exists in an array, use Array.prototype.includes().

It checks all the items of the array, and whichever the first item meets, the condition is going to print.

If more than one item meets the condition, then the first item satisfying the condition is returned.

Suppose that you want to find the first odd number in the array.

The argument function checks whether an argument passed to it is an odd number or not.

Javascript array find() function calls an argument function for every item of the array.

The first odd number for which argument function returns true is reported by the find() function as the answer.

#Javascript find() syntax

The syntax of the array find() method is the following.

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

Arguments

The function takes three arguments:

element:
This is the current item being processed by the function.

index
This is the index of the current item being processed by the function.

array:
This is the array on which the array.filter() function was called.

Another argument which is thisValue. It used to tell the function to use the array value when executing an argument function.

#Javascript find() example 

We will use a Node.js to write the Javascript files.

So let us create the file called the app.js and add the following code.

// app.js

var data = [20, 18, 15, 10, 9];

var found = data.find(function(element) {
  return element < 12;
});

console.log(found);

So, we have written one condition, and if any array item satisfies this condition, then it will return the value of that element, and the further checking of items inside an array will be stopped.

Here, both the values 10 and are less than 12, but still, we got the 10 because 10 value of an item is first inside an array.

So only 10 will return and not 9. So, if the satisfying condition element is found inside an array, then it will immediately return, and no further checking is required.

➜  es git:(master) ✗ node app
10
➜  es git:(master) ✗

We can write the above function in ES6 standard, like the following.

// app.js

const data = [20, 18, 15, 10, 9];

let found = data.find(element => element < 12);

console.log(found);

The answer will be the same as previous, but it is the much lighter syntax.

Now let us take a scenario where undefined is found.

// app.js

const data = [20, 18, 15, 10, 9];

let found = data.find(element => element < 9);

console.log(found);

In the above example, all the elements are greater than 9; that is why the output will be undefined.

#Pure Function

Javascript Array Find method is a pure function because it does not mutate an array on which it is called. Instead, it will return a value that satisfies its condition.

#Find an item using Find() Method in Javascript

Now, write the following code.

// app.js

const fruits = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

const getFruit = fruits.find(fruit => fruit.name === 'apples');

console.log(getFruit);

Here, only one object will be returned if the condition is met successfully.

  es git:(master) ✗ node app
{ name: 'apples', quantity: 2 }
➜  es git:(master) ✗

So, whenever we have a scenario where we need to get a value of the first element in an array that satisfies the provided testing function, we can use Array.find() method in JavaScript.

#Javascript array search

Let’s take an example of whether the person is an adult or not. If we find the first value from the array which satisfies the criteria, then it will return that value.

See, we are searching for an item in the array using javascript find() function.

// app.js
let ages = [6, 18, 19, 21];

let checkAdult = age => {
  return age >= 18;
}

console.log(ages.find(checkAdult));

In the above code, if the first array element found greater than or equal to 18, then it will return in the output. Now, see the output.

➜  es git:(master) ✗ node app
18
➜  es git:(master) ✗

#Javascript find element in array

As of ECMAScript 2018, we can use Javascript includes() function. Javascript Array includes() method determines whether an array contains the specified item. It returns true if it consists of an element, otherwise false, as not including the item in the array.

If you want to support IE or other older browsers, then try the following code.

// app.js
 function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

In the above code, we have used the Javascript indexOf method. So, this is how to search value in an array in javascript.

#Javascript find object in array

Let’s say I have an array of unnamed objects, which contain the array of named objects, and we need to get the object where “name” is “some string.” See the following programming example.

// app.js
 search = (key, inputArray) => {
  for (let i=0; i < inputArray.length; i++) {
      if (inputArray[i].name === key) {
          return inputArray[i];
      }
  }
}

let arr = [
  { name:"Krunal", value:"Engineer", other: "Author" },
  { name:"Ankit", value:"MCA", other: "Author" }
];

let resultObject = search("Krunal", arr);
console.log(resultObject);

Okay, so in the above code, first we have a user-defined function called search function which accepts two arguments. One is the input object key, and the other is an input array.

It iterates the inputArray and compares the key with the array’s name property. If it matches, then returns the whole object. See the below output.

Javascript Array Find Example | Javascript Array Search

We can also use find() function to get the same value. See the following code.

// app.js
 let arr = [
  { name:"Krunal", value:"Engineer", other: "Author" },
  { name:"Ankit", value:"MCA", other: "Author" }
];

let obj = arr.find(data => data.name === 'Krunal');

console.log(obj);

It will give us the same output, but it is in ES6 style arrow function.

#Javascript find in string

Javascript search() method searches a string for a specified value and returns the position of the match. The search value can be a string or a regular expression. This method returns -1 if no match is found.

#Find prime number in js array

The following example finds the item in the array that is the prime number (or returns undefined if there is no prime number):

// app.js

const isPrime = (element, index, array) => {
  let start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) { return false; } } return element > 1;
}

console.log([4, 6, 8, 11].find(isPrime));
console.log([9, 1, 21, 13].find(isPrime));

See the output.

➜  es git:(master) ✗ node app
11
13
➜  es git:(master) ✗

#Browser Support

FEATURE BASIC SUPPORT
Chrome 45
Edge Yes
Firefox 25
Internet Explorer No
Opera 32
Safari 8
Android WebView Yes
Chrome for Android Yes
Edge mobile Yes
Firefox for Android 4
Opera Android Yes
iOS Safari 8

 #Conclusion

  1. The test must be provided as the function.
  2. The find() method executes a callback function once for each element in the array until it finds a value that returns true.
  3. If nothing passes a test, then undefined is returned.
  4. The find() does not mutate or change the original Array. So it is a pure function.
  5. Whenever we need to get the value of the first element in the array that satisfies the provided testing function at that time, we use Array.find() method in JavaScript.

You can also check out the reference for the array.find() function on official Mozilla docs.

Finally, Javascript Array Find Example | Javascript Array Search Tutorial is over.

Recommended Posts

Javascript Array isArray Tutorial

Javascript Array ToString Example

JavaScript Array Reverse Example

Javascript Array Values Example

Javascript Array Includes Example

1 Comment
  1. indra says

    it`s a great tutorial thanks

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.