AppDividend
Latest Code Tutorials

Javascript array find: How to Find Element in Javascript

The array find() function in JavaScript returns the value of the first element in an array that passes a provided function test. Let’s deep dive into the array find() method.

Javascript array find

Javascript array find() is a built-in function used to get a value of the first element in the Array that meets the provided condition. The find() function accepts a function, thisValue, element, index, and array and checks all the array elements, and whichever the first element meets, the condition will print.

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

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 Array.prototype.indexOf(). If you need to find if the value exists in an array, use Array.prototype.includes().

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.

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

Syntax

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

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

Parameters

The function takes the following 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 is thisValue. It tells the function to use the array value when executing an argument function.

Example 

We will use Node.js in this example to run the javascript code.

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. If any array item satisfies this condition, it will return the value of that element, and the further checking of elements inside an array will be stopped.

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

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

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

ES6 Array find()

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 the previous one, but it is a 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; 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.

Finding an element in an array using find()

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

To search an element in the array in JavaScript, use the array find() method. The find() method checks if an array contains the element or not. Let’s take an example of whether the person is an adult. If we find the first value from the array, which satisfies the criteria, it will return it.

We are searching for an item in the Array using the 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 is found greater than or equal to 18, it will return in the output. Now, see the output.

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

Finding an element in the JavaScript array

To find if an array contains an element in a JavaScript array, use the array includes() method. Javascript includes() is a built-in array function that determines whether an array contains the specified element. It returns true if it consists of an element, otherwise false, without including the element in the array.

As of ECMAScript 2018, we can use the Javascript includes() function. 

If you want to support IE or other older browsers, 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.

Finding the object in the JavaScript array

To find an object in a JavaScript array, use the array.find() method. The find() method searches the provided object inside the array, and if the method finds it, it returns the object.

I have an array of unidentified 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 the 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 it returns the whole object. See the below output.

Javascript Array Find Example | Javascript Array Search

We can also use the 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 the ES6 style arrow function.

Finding a string in the JavaScript

To find a string in JavaScript, use the string search() method. 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.

Finding prime number in array

The following example finds the element 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) ✗

Using ES6 arrow function and destructuring

We can use the ES6 arrow function and object destructuring in Javascript with the javascript find() function. The code looks clearer, less buggy, and easy to understand. See the following code.

// app.js

const fav = [
  { actress: 'Millie Bobby Brown', age: 16 },
  { actress: 'Kiernan Shipka', age: 19 },
  { actress: 'Emma Watson', age: 29 }
];

const result = fav.find(({ actress }) => actress === 'Millie Bobby Brown');

console.log(result)

Output

node app
{ actress: 'Millie Bobby Brown', age: 16 }

If the actress is Millie Bobby Brown in the above code, it will give us that object with two properties; otherwise, it will provide us with undefined.

Polyfill

The JS array find() method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations. However, you can use the polyfill Array.prototype.find() the following snippet.

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function (predicate) {
      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    },
    configurable: true,
    writable: true
  });
}

If you want to support obsolete JavaScript engines that don’t support Object.defineProperty, it is best not to polyfill the Array.prototype, as you cannot make it non-enumerable.

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, we use Array.find() method in JavaScript.

Recommended Posts

Javascript Array isArray()

Javascript Array toString()

JavaScript Array reverse()

Javascript Array values()

Javascript Array includes()

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.