5

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

2
  • findIndex implementation would be something like : Loop through the array, pass each element to the callback passed and check the response. If its true, break the loop and return the index of element otherwise send a default value preferably -1 Commented Jun 20, 2017 at 19:28
  • 2
    The Array.prototype.findIndex() is taking a custom comparison function, and returning the index of the first true it finds, the => is an Arrow Function Commented Jun 20, 2017 at 19:35

1 Answer 1

9

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's right. Additionally I want to point out there is a good explanation here: stackoverflow.com/documentation/javascript/5007/…
May I ask additionally? The parameter of the function is "quoteEl: Quote" , i.e. a new defined variable of the type Quote that will be set by each element of the "quotes" array, right? But where is the "quote.id" coming from. Is it defined somewhere outside this piece of code?
(quoteEl: Quote) means the function is expecting to be passed an object of type Quote, which is indeed not defined in the code you provided.
@BenSpi sadly stack documentation has been shut down, so the link you provided above is no longer is valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.