Home > Back-end >  I don't get the concept of findIndex()
I don't get the concept of findIndex()

Time:09-19

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

I don't get this output. Why 3? There are only 2 of it. Isn't it?

CodePudding user response:

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function.

The output is 3 since the first element that is greater than 13 is 130.

5, 12, 8, 130, 44
0  1   2  3    4

The output is the index of the first element that satisfies the condition.

CodePudding user response:

lets look this an example

const array = [1,2,3,4,5,6,7]
const array1 = [1,3,4,7,14]
const array2 = [120, 100, 5, 9]

const fun =(ar)=>{
const getIndex = ar.findIndex((e)=> e > 13)
return getIndex;
}
console.log(fun(array)) // this checks iteration from 0 to array.length so here its not found then we got -1 
console.log(fun(array1)) // this case we got index at 4 because it has looped from index 0 to end and it did't found any element from index 0 to index 3
console.log(fun(array2)) // here element is looped and get found at first iteration then it gives the first matched value index 0

CodePudding user response:

The findIndex() method returns the index (position) of the first element that passes a test. Hence output 3 is correct. number 130 at index 3 is the first element to pass test of ( element > 13 )

CodePudding user response:

As the function definition says: "The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned."

So your case will return 3, because 130 is the first value encountered which is bigger than 13, and it's at the third position, because arrays start from zero!

CodePudding user response:

There might be two large numbers, but findIndex doesn't count all entries that pass the truth test. It returns the index of the first element's index to pass it. Consider this:

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = function(element, index) {
    console.log('index:', index, 'element:', element, element > 13 ? 'Found. End.' : 'Not found. Continue')
    return element > 13
}

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

It logs the following:

  • index: 0 element: 5 Not found. Continue
  • index: 1 element: 12 Not found. Continue
  • index: 2 element: 8 Not found. Continue
  • index: 3 element: 130 Found. End. → Therefore, the result is 3
  • Related