0

i want to loop through an array of application numbers to see if there is a match using indexOf.

currently my array looks like..

array:

"applications":[  
         "123456",
         "224515",
         "658454",
         "784123"
      ]

my controller:

$scope.hasApplicationNumber = function (appNo) {
        var applicationsArray = applications;
        return applicationsArray.indexOf(appNo);
      }

html:

<span ng-if="hasApplicationNumber(784123)">Its a Match!</span>
1
  • indexOf doesn't return a boolean. Commented May 9, 2017 at 19:50

3 Answers 3

1

DEMO

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.applications = [  
         "123456",
         "224515",
         "658454",
         "784123"
      ];

    $scope.hasApplicationNumber = function (appNo) {
        var res = $scope.applications.filter(item => { return item.indexOf(appNo) != -1; });
        return (res.length) ? true : false;
      }  
});

<div ng-app="myApp" ng-controller="MyCtrl">
  <span ng-if="hasApplicationNumber(784123)">Its a Match!</span>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Am I misunderstanding something? Why not just use Array.prototype.includes?

Disclaimer: This uses ES6 arrow syntax,

$scope.hasApplicationNumber = function (appNo) {
    return applicationsArray.map(no => Number(no)).includes(appNo);
}

JS Fiddle Link: https://jsfiddle.net/3p4mq9qL/

Edit: Fixed if you want to look by number (when the array is string)

1 Comment

Worth noting that this uses ES6. A beginner might not know that, and get frustrated trying to use ES6 without Babel or similar.
0

indexOf method returns a index of matched number. So you should be checking if its greater than -1. Over here you were checking number instead of string(array member), so before checking you have to convert all array to Number and check otherwise check appNo to string then find it in an array.

$scope.hasApplicationNumber = function (appNo) {
    var applicationsArray = applications;
    //return applicationsArray.indexOf(appNo.toString()) > -1;
    //OR
    //return !!~applicationsArray.map(Number).indexOf(appNo); //then check number
    //OR
    return !!~applicationsArray.indexOf(appNo.toString());
}

3 Comments

If you want to confuse people you can use return !!~applicationsArray.indexOf(appNo);
Bang bang squiggle
@Joe cool man. That's fantastic, I made an update to answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.