jeremy
jeremy

Reputation: 433

using indexOf to see if there is a match in an object in angularJS

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>

Upvotes: 0

Views: 2292

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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());
}

Upvotes: 0

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

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>

Upvotes: 1

Bergur
Bergur

Reputation: 4057

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)

Upvotes: 0

Related Questions