alsco77 alsco77 - 3 months ago 21
Javascript Question

Return index value from filter method javascript

So I have an array of objects in my angular controller, and 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..

$scope.indexOfField = function(fieldId) {
return $scope.model.fieldData.filter(function(x) {
if (x.Id === fieldId) {
return // ???????
}
});
}

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

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

$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
    }