[Vuejs]-FindIndex outcome is true, so why does it return -1

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

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 :)

},

Leave a comment