Basics of Javascript · Array · findIndex() (method)

Jakub Korch
Nerd For Tech
Published in
5 min readJan 4, 2024

This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.

Heidy ho, dev newbs! Previously we discussed the method find() that can return a first element fitting the given conditions. Today’s method findIndex() is very similar. The only difference is that it does not return the value, but rather the index. Let’s explore it together!

The method findIndex() returns the index of the first element in an array that satisfies the provided testing function. If no element satisfies the testing function, -1 is returned.

This method has of course a callback function as an argument. It can be declared as an arrow function or a classic JavaScript function. The callback function itself has three arguments — element being processed in the array, index of the current element and the array that the method has been called upon. The callback function should return truthy value to indicate that element has matched the condition or falsy value otherwise. Let’s see the basic usage of the method findIndex() in the first block of code.

// Example 1
// basic usage

console.log("EXAMPLE 1");
console.log("--------------------------------------------------");

let greetings = ["hello", "ola", "ciao", "hallo", "konichiwa", "ni hao", "namaste"];

// find first greeting longer than 6 characters
console.log(greetings.findIndex((word) => word.length > 6));
// returns 4

let numbers = [11,164,785,325,4126,98,7,4,5,62,247];

function myCustomCondition(element, index){
if((element > 200) && (index % 2 == 1))
return true;
}

// get element > 200 with odd index
console.log(numbers.findIndex(myCustomCondition));
// returns 3

let charSequence = ["a", "b", "d", "c" , "g", "f"];

function checkAscencion(element, index, array){
if(index == 0)
return false;
if(element > array[index - 1])
return false
return true
}

// find first element not ascending
console.log(charSequence.findIndex(checkAscencion));
// returns 3

The basic examples cover using the method in a typical scenario. No exceptions or edge cases here. First call to the method on an array with greetings gets us the index of the first element longer than 6 characters. It is number 4.

The second call to method uses both element and index and it returns the index of the first element greater than 200 while having an odd index. The result was index 3.

The last call to a method utilizes all three arguments and it checks the index of the first element in the array smaller than the previous one. We get the index 3 as a result.

The arrays we work with do not have to consist only of primitive values. The second block of code will showcase how we can easily work with objects as well.

// Example 2
// working with objects

console.log("EXAMPLE 2");
console.log("--------------------------------------------------");

let fruits = [
{ name: "apple", sweetness: 5 },
{ name: "strawberry", sweetness: 7 },
{ name: "lemon", sweetness: 0 }
];

function isReallySweet(element){
if(element.sweetness > 5)
return true;
return false;
}

// find first fruit with sweetness greater than 5
console.log(fruits.findIndex(isReallySweet))
// returns 1

// the same principle, but with arrow function and destructuring
console.log(fruits.findIndex( ({ sweetness }) => sweetness < 4));
// returns 2

Both examples deal with an array that contains 3 objects representing three different types of fruits. Each item has two properties — name and sweetness.

In the first example, we are using an old-school type of a JavaScript function. It checks the sweetness of a given element and if it is greater than 5 it returns true. The given object is returned.

The second example shows how to achieve the same thing, but this time using the arrow function and destructuring to get the sweetness property directly without having to call the object itself. The second example searches for the first item with sweetness less than 4.

The next section of examples will show how the findIndex() method handles sparse arrays. Surprise, surprise! Just like find() method also findIndex() method visits empty slots and they are treated like fields with the value of “undefined”. Let’s make sure it is really like that in the next block of code.

// Example 3
// sparse arrays

console.log("EXAMPLE 3");
console.log("--------------------------------------------------");

let myArray = [1, 0, , , 84, 14, , 123];

// show each iteration using arrow function without return value
myArray.findIndex((element, index) => {
console.log(`Element at position [${index}] has value: ${element}`);
});

Just like with the find() method, I am cheating, because instead of condition, I just iterate through all items to showcase that even the undefined and empty slots are included.

Last exercise for today will show you how to work with an array-like object. Let’s check it out.

// Example 4
// array-like object

console.log("EXAMPLE 4");
console.log("--------------------------------------------------");

const arrayLike = {
length: 3,
0: "k",
1: "i",
2: "d",
3: "s"
};

function checkDescencion(element, index, array){
if(index == 0)
return false;
if(element < array[index - 1])
return false
return true;
}

// find char larger that previous one in an array
console.log(Array.prototype.findIndex.call(arrayLike, checkDescencion));
// returns -1

arrayLike.length = 4

// find char larger that previous one in an array
console.log(Array.prototype.findIndex.call(arrayLike, checkDescencion));
// returns 3

Just like with any other Array method, the length property is the ultimate guide for the range of accessible digit properties. Because of that, only the indices 0, 1 and 2 are taken into consideration when method findIndex() is invoked. Since each of them is less than the previous one, our findIndex() method does not find anything and returns -1.

But if we change the length property to a higher number that would include the last digit property, suddenly the condition function finds the candidate larger than its predecessor. Returned value will be 3.

Okay, that was everything I had for today. Examples are written and executed. Special cases are mostly handled. Sure there’s many more, but you will have to deal with those yourselves.

I am thankful for you sticking until the end of the lesson. If you like the content I make, consider subscribing to my channel, liking the video and clicking that notification bell to get notified about the next video that will come out soon. Until then…see ya all!

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Jakub Korch
Jakub Korch

Written by Jakub Korch

Web enthusiast, programmer, husband and a father. Wannabe entrepreneur. You name it.

No responses yet