2

I can't seem to make array.findIndex work and I am sure that there should be a match in the array I am searching for but findIndex always returns a -1.

let index = state.bag.findIndex((it) => {
    it.id === item.id
    console.log(it.id,it.id===item.id,item.id);
  })
  console.log(index);

I get the following console log:

00SEEB0BASU900XS false 00SEEB0BASU900S index.js:48
00SEEB0BASU900S true 00SEEB0BASU900S index.js:48
00SEEB0BASU900M false 00SEEB0BASU900S index.js:48
00SEEB0BASU900L false 00SEEB0BASU900S index.js:48
00SEEB0BASU900XL false 00SEEB0BASU900S index.js:48
00SEEB0BASU900XXL false 00SEEB0BASU900S index.js:48
-1 index.js:50

As you can see it finds a truthy value and thus should return the index of the object array.

I am really stumped and any help is appreciated.

EDIT:
Adding the RETURN did work, although just for my learning path, in the MDN example for findIndex, there was no RETURN.

const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];

const index = fruits.findIndex(fruit => fruit === "blueberries");

console.log(index); // 3
console.log(fruits[index]); // blueberries

2 Answers2

0

Because you are forget to return the condition inside the callback

Array#findIndex

enter image description here

let index = state.bag.findIndex((it) => {
    return it.id === item.id
    //console.log(it.id,it.id===item.id,item.id);
  })
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • 1
    *facepalm That is why there should be peer reviews on your own code. Sometimes the answer is in plain-sight but you cannot see it. Thanks @prasanth. – FDelioncourt May 03 '20 at 08:06
0

let index = state.bag.findIndex((it) => {
    return it.id === item.id
    console.log(it.id,it.id===item.id,item.id);
  })
  console.log(index);
these ecma 6 methods require return otherwise it will not effect able
arslan
  • 1,064
  • 10
  • 19