0

I am having an array of objects in which i would like to find the index of the selected object when i used the indexOf i am getting the value as -1 can anyone tell me how to find the indexOf of an object in javascript

var a = [{id:2322,location:"Erode",mobile_no:"123456789",name:"andhr",type:"Farmer"}, {id:2323,location:"Coimbatore",mobile_no:"123456789",name:"andhraK",type:"Farmer"}, {id:2324,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}];

a.indexOf({id:2322,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"});
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72

1 Answers1

1

That is because those are not the same.

Each Object gets it's own memory address.

address 1: {id:2322,location:"Erode",mobile_no:"123456789",name:"andhr",type:"Farmer"}, 
address 2: {id:2323,location:"Coimbatore",mobile_no:"123456789",name:"andhraK",type:"Farmer"}, 
address 3: {id:2324,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}

Then in the array it's stored like:

var a = [(point to address 1), (point to address 2), (point to address 3)]

When you are looking for the object you're actually doing

address 4: {id:2322,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}
a.indexOf((point to address 4));

What you need to do is store your own references to those objects:

var A = {id:2322,location:"Erode",mobile_no:"123456789",name:"andhr",type:"Farmer"}; 
var B = {id:2323,location:"Coimbatore",mobile_no:"123456789",name:"andhraK",type:"Farmer"};
var C = {id:2324,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}

var arr = [A, B, C];
console.log(arr.indexOf(B));
Tschallacka
  • 27,901
  • 14
  • 88
  • 133