Soumya Gangamwar Soumya Gangamwar - 3 months ago 7
Javascript Question

How to find the index of an object in an array by checking property value in JavaScript?

I have an array like

$scope.myArray = [{
columnName:"processed1",
dataType:"char"
},
{
columnName:"processed2",
dataType:"char"
},
{
columnName:"processed3",
dataType:"char"
}
]


I want find the index of object which property value satisfy "processed2".

How can it do it? I tried using
array.indexOf()
method but I got response -1.

Is there any other way?

Answer

Use Array#findIndex, The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned.

Array#indexOf will fail as array contains objects, indexOf() tests the element using triple-equals operator and object is equals to object if it refers to same memory-location

var myArray = [{
  columnName: "processed1",
  dataType: "char"
}, {
  columnName: "processed2",
  dataType: "char"
}, {
  columnName: "processed3",
  dataType: "char"
}];
var index = myArray.findIndex(function(el) {
  return el.columnName == 'processed2';
});
console.log(index);

Comments