2
let database = [{
        name: 'James Bond',
        code: '007'
    },
    {
        name: 'El',
        code: '11'
    }
]

let subject = {
    name: 'James Bond',
    code: '007'
}

database.indexOf(subject)

This returns -1. I found similar questions here on SO but they were all mostly asking to find index of the object by comparing it to a key value pair.

Aditya
  • 677
  • 2
  • 9
  • 15
  • The reason is that you are trying to look it up by a *different* object. `database[0]` and `subject` are different objects, even if they have the same values. They point to different memory addresses. You do need to compare the values to see if the objects look the same. Alternatively, you can do what you want if you had `database[0] = subject` and then `database.indexOf(subject)` will be correct. – VLAZ Dec 25 '17 at 12:20

2 Answers2

1

From DOCS

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

Use findIndex

DEMO

let database = [{
        name: 'James Bond',
        code: '007'
    },
    {
        name: 'El',
        code: '11'
    }
]

let subject = {
    name: 'James Bond',
    code: '007'
}

console.log(database.findIndex(x => x.name=="James Bond"))
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0
let subInd ;
database.forEach(function(ele,index){
  if(ele.name == subject.name && ele.code == subject.code ){
    subInd=index;
  }          
});
console.log(subInd);
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Madan Sandiri
  • 400
  • 1
  • 3
  • 11