Return index value from filter method javascript
Solution 1:
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 );
Solution 2:
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
}
Solution 3:
From the Array.prototype.filter
documentation:
callback is invoked with three arguments:
- the value of the element
- the index of the element
- the Array object being traversed
However you should probably be using the some
function if there is only one instance in your array (as it will stop as soon as it finds the first occurrence), and then find the index using indexOf
:
var field = $scope.model.fieldData.filter(function(x) {
return x.Id === fieldId;
})[0];
var index = $scope.model.fieldData.indexOf(field);
Or iterate the array until you find the correct element:
var index;
$scope.model.fieldData.some(function(x, i) {
if (x.Id === fieldId) return (index = i);
});