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
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With