-1

Having the following array:

  const options = [
    {
      id: 'Coffee',
      type: 'radio-group',
    },
    {
      id: 'Tea',
      type: 'radio-group',
    },
    {
      id: 'Milk',
      type: 'radio-group',
      disabled: true,
    },
  ];

and the object:

const toCheck =  { id: 'Coffee', type: 'radio-group'};

Because options[0] is equal to toCheck, shouldn't options.indexOf(toCheck) return 0?

It returns -1, is it a way to return the desired value?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • Different objects with the same values aren't `===` to each other. You will need to use `.findIndex` to find the index of an object with the same properties. – CertainPerformance Jan 04 '23 at 00:25

1 Answers1

1

Consider using an object property, here I used the id for these examples:

const options = [{
    id: 'Coffee',
    type: 'radio-group',
  },
  {
    id: 'Tea',
    type: 'radio-group',
  },
  {
    id: 'Milk',
    type: 'radio-group',
    disabled: true,
  },
];
let c = options.findIndex((x) => x.id === 'Coffee');
console.log(c);
let m = options.findIndex((x) => x.id === 'Milk');
console.log(m);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100