JavaScript Find First Occurrence in Array

JavaScript find first occurrence in array; Through this tutorial, i am going to show you how to find first occurrence in array using JavaScript find() method.

JavaScript Find First Occurrence in Array

Using javaScript find() method, you can find first occurrence in javaScript array.

See the following syntax, parameters and example of javaScript find() method; As shown below:

Syntax of JavaScriptfind() method

The following syntax of the javaScript find() method:

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

Parameters of JavaScriptfind() method

The find() takes two parameters:

  • The first one is the callback function and it’s optional.
  • The second one is used as this inside the callback.

Example 1 – To find first occurrence in array javaScript

Let, you have a numeric array and want to search the first odd number(occurrence) in array, you can use javaScript find() method.

See the following example:

let numbers = [1, 2, 3, 4, 5];
console.log(numbers.find(e => e % 2 == 1));

Output:

1

And want to find first even number (occurrence) in an array, you can find, as following:

let numbers = [1, 2, 3, 4, 5];
console.log(numbers.find(e => e % 2 == 0));

Output:

2

Example 2 – JavaScript find first occurrence from object in array

Let, you have a list of computers object array with name and price properties as follows:

let computers = [{
    name: 'Dell',
    price: 60000
}, {
    name: 'HP',
    price: 50000
}, {
    name: 'Apple',
    price: 80000
}];

The following javascript code uses the find() method to find the first computer whose price is greater than $ 60000.

let computers = [{
    name: 'Dell',
    price: 60000
}, {
    name: 'HP',
    price: 50000
}, {
    name: 'Apple',
    price: 80000
}];
console.log(computers.find(c => c.price > 60000));

Output:

{name: "Apple", price: 80000}

Conclusion

In this tutorial, you have learned how to use the JavaScript Array’s find() method and using this method how to find the first occurrence of an element in an array.how to get the first index of an array in javascript.

More JavaScript Tutorials

Recommended:-JavaScript Arrays

Be First to Comment

Leave a Reply

Your email address will not be published.