0

I've got the following function

 expandActions(e) {
    const index = this.menuItems[this.element].findIndex((menu) => {
      console.log(menu.type === e) // this returns true
      menu.type === e
    })
    console.log(index) // this returns -1
  }

this.element = paragraph e = font

Json:

{
"paragraph": [
    {
        "type": "font",
        "icon": "font",
        "actions": [
            {
                "do": "size",
                "icon": "text-height"
            },
            {
                "do": "letter-spacing",
                "icon": "text-width"
            },
        ]
    },
    {
        "type": "text-align",
        "icon": "align-left",
        "actions": [
            {
                "do": "align-right",
                "icon": "align-right"
            },
            {
                "do": "align-justify",
                "icon": "align-justify"
            },
        ]
    }
]

}

Why is FindIndex returning -1 if there is a match with an index? If the function returns true is should return an index right?

DutchPrince
  • 333
  • 2
  • 16
  • You have to return the result of `menu.type === e`. There's only an implicit `return` for arrow functions without a body wrapped in `{ }` – Andreas Aug 29 '20 at 12:09
  • Could be a dupe of: [When should I use `return` in es6 Arrow Functions?](https://stackoverflow.com/questions/28889450/when-should-i-use-return-in-es6-arrow-functions) – Andreas Aug 29 '20 at 12:15

3 Answers3

1

You need to return from the callback function

expandActions(e) {
  const index = this.menuItems[this.element].findIndex(menu => menu.type === e)
  console.log(index) // this returns -1
},
brk
  • 48,835
  • 10
  • 56
  • 78
  • 1
    _"You need to return from the callback function"_ - But then there's no `return ...` and you rely on the implicit `return` but you don't mention it... – Andreas Aug 29 '20 at 12:10
  • @Andreas _Parentheses are optional when there's only one parameter name_ – brk Aug 29 '20 at 12:11
  • And how is this comment relevant for your answer, my comment and the implicit `return`? o.O – Andreas Aug 29 '20 at 12:13
1

you need add return before menu.type === e

1

your 'findIndex callback' must return something. If the callback returns truthy, 'findIndex' will return the first index value that satisfy. If the callback returns falsy, 'findIndex' will return -1. In the case of your code, the callback returns nothing, or 'undefined' that is falsy, so it will never get some index.

expandActions(e) {
const index = this.menuItems[this.element].findIndex((menu) => {
  console.log(menu.type === e) // this returns true
  return menu.type === e // just added 'return' at the begin of this line
})
console.log(index); // try now :)

},