0

The x.name and imgname have the same type (string) and the same value "comcardpro_capsule_model_2". But why the findIndex() function return -1? Please explain it to me.

findPicture(imgname): number {
   return this.info.comcardList.findIndex(x => {
      x.name === imgname;          // result in console:
      console.log(imgname)         // comcardpro_capsule_model_2
      console.log(typeof imgname)  // string
      console.log(typeof x.name)   // string
      console.log(x.name);         // comcardpro_capsule_model_2
   })
  }

Expect result will be index of the element in array not -1.

2
  • 2
    you need add a return statement Commented Oct 16, 2019 at 13:58
  • 1
    Because you're NOT returning the result of the comparison. That's all that's going on here. Commented Oct 16, 2019 at 14:11

3 Answers 3

5

Your findIndex callback always returns undefined, you should instead return x.name === imgname;

The findIndex function essentially does something like

if (findIndexCallback(element)) return index;

for each element of the array. So if your function returns nothing (undefined), the fallback value of -1 meaning "not found" is returned.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex for full documentation.

Sign up to request clarification or add additional context in comments.

3 Comments

It works, thank you. But can you explain why we can not remove the 'return' in return x.name === imgname;
Single-statement/non-bracketed arrow functions don't need a return statement because it is implicit. () => 5 is a function that returns 5. () => { 5; } is a function that returns undefined. If your function were just x => x.name === imgname it would also work.
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; const index = fruits.findIndex(fruit => fruit === "blueberries"); console.log(index); // 3 console.log(fruits[index]); // blueberries
1

you need add a return statement on your findIndex

findPicture(imgname): number {
  return this.info.comcardList.findIndex(x => {
     return x.name === imgname;          // result in console:
  })

}

Comments

1

You need to return the result from your findIndex function.

findPicture(imgname): number {
    return this.info.comcardList.findIndex(x => {
    return x.name === imgname;
    });
 }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.