Return index value from filter method javascript
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
$scope.indexOfField = function(fieldId) {
var i;
return $scope.model.fieldData.forEach(function(x, index) {
if (x.Id === fieldId) {
i = index;
}
});
// use i
}
or even better to use for
as you can't stop forEach when you have found your id.
$scope.indexOfField = function(fieldId) {
var fieldData = $scope.model.fieldData,
i = 0, ii = $scope.model.fieldData.length;
for(i; i < ii; i++) if(fieldData[i].Id === fieldId) break;
// use i
}
The .findIndex()
method returns the index of the first element of the array that satisfies a condition given by a function. If the function returns false
for all elements of the array, the result is -1
.
See the documentation here.
In my example, x
is an item for each iteration and I use cross function for my condition.
const datas = [];
const fieldId = 5;
let index = datas.findIndex( x => x.Id === fieldId );