Soumya Gangamwar
Soumya Gangamwar

Reputation: 1022

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 I do it? I tried using array.indexOf() method but I got response -1

Upvotes: 4

Views: 7692

Answers (2)

Parthasarathy
Parthasarathy

Reputation: 2818

You can use a simple for loop.

for(var i=0;i < $scope.myArray.length; i++)
{
  if($scope.myArray[i].columnName == 'processed2') {
    // Do something with found item
    break;
  }
}

Upvotes: 1

Rayon
Rayon

Reputation: 36599

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

Upvotes: 5

Related Questions