I have an array of objects in my angular controller.
I want to return the value of the index of the field within the array which has a matching ID to my parameter.
There will only be one object in the array with a matching fieldId
..
JavaScript
x
6
1
$scope.indexOfField = function(fieldId) {
2
return $scope.model.fieldData.filter(function(x) {
3
if (x.Id === fieldId) return // ???????
4
});
5
}
6
Advertisement
Answer
You can’t return index from filter method.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
You can use forEach
JavaScript
1
10
10
1
$scope.indexOfField = function(fieldId) {
2
var i;
3
return $scope.model.fieldData.forEach(function(x, index) {
4
if (x.Id === fieldId) {
5
i = index;
6
}
7
});
8
// use i
9
}
10
or even better to use for
as you can’t stop forEach when you have found your id.
JavaScript
1
7
1
$scope.indexOfField = function(fieldId) {
2
var fieldData = $scope.model.fieldData,
3
i = 0, ii = $scope.model.fieldData.length;
4
for(i; i < ii; i++) if(fieldData[i].Id === fieldId) break;
5
// use i
6
}
7