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.

1
  • 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. Commented Dec 25, 2017 at 12:20

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0
let subInd ;
database.forEach(function(ele,index){
  if(ele.name == subject.name && ele.code == subject.code ){
    subInd=index;
  }          
});
console.log(subInd);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.