JavaScript Find First Element Position In Array

To find first index of element in array javaScript; Through this tutorial, i am going to show you how to find the first element index in an array javaScript.

JavaScript Find First Element Index In Array

Using the JavaScript array findIndex() method, you can find index of first element of the given array that satisfies the provided function condition.

Syntax of the JavaScript findIndex() method

The following syntax of the javaScript findIndex() method:

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

Parameters of the JavaScript findIndex() method

The findIndex() 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 – JavaScript get first element position from array

Let, you have a numeric array and want to search the first odd number position in it, you can use these findIndex() method for these.

See the following example:

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

Output:

0

If you want to find first even number index or position in an array, you can find the following:

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

Output:

1

Example 2 – JavaScript find index of object in array

Let, you have a list of computers objects 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 findIndex() method to find the first computer position in an array, whose price is greater than $ 60000.

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

Output:

2

Conclusion

In this tutorial, you have learned how to use the JavaScript Array’s findIndex() method and using this method how to find the first occurrence Index or position in an array.

More JavaScript Tutorials

Recommended:-JavaScript Arrays

One Comment

  1. Kagiso said:

    Beautiful work you are doing here. Keep it up!

    May 19, 2021
    Reply

Leave a Reply

Your email address will not be published.