Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding findIndex in Javascript / Typescript

I am working on a piece of JS code. In a tutorial I found a piece of code I don't understand:

const position = this.quotes.findIndex((quoteEl: Quote) => {
  return quoteEl.id == quote.id;
});

I think the person who wrote the code stuffed a lot of different pieces into this line. Can somebody help me bring that into a more "easy to understand" form?

For example, the argument of the findIndex method can probably written in a separate function, right?

Thanks, Benjamin

like image 306
Ben Spi Avatar asked Jun 20 '17 19:06

Ben Spi


People also ask

How does findIndex work in JavaScript?

The findIndex() method executes the callbackFn function once for every index in the array, in ascending order, until it finds the one where callbackFn returns a truthy value. If such an element is found, findIndex() immediately returns the element's index.

What is difference between find and findIndex in JavaScript?

Find() will return the value of the first element based on the provided condition and returns undefined if none of the elements passed the condition. FindIndex() will return the index of the first element based on the condition and returns -1 if none of the elements passed the condition.

What is the difference between findIndex and indexOf?

findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise. indexOf - Returns the index of the first occurrence of a value in an array.

How do you find the index of an element in array TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

findIndex calls the passed function with each element of the array and returns the index of the first element that returned true, or -1 if none did.

This is your callback function

(quoteEl: Quote) => {
  return quoteEl.id == quote.id;
}
like image 59
pishpish Avatar answered Sep 22 '22 15:09

pishpish