9

I'm trying to use JavaScript's find() function on an AngularJS array. That's legal, right...?

This very simple code is causing me some problems. It's saying that the return value from $scope.names.find(name1) is not a function.

TypeError: Name1 is not a function

if($scope.names.find(name1) !== name1) {
   $scope.names.push(name1);
}

I have also tried...

if($scope.names.find(name1) === undefined) {
   $scope.names.push(name1);
}

and

if(!$scope.names.find(name1)) {
   $scope.names.push(name1);
}

This if is in a loop. If name is not in the array, then add it. If it is already in the array, don't add it.

Here is the loop:

angular.forEach($scope.names1, function (name1) {
    angular.forEach($scope.names2, function (name2) {
        if (name1 === name2) {
            $scope.names.push(name1);
        }
    });
    if ($scope.names.find(name1) === name1) {
        $scope.names.push(name1);
    }
});

I don't know what the error is referring to exactly. I must be misusing find().

7
  • 4
    As you can see in Docs find takes callback function as argument, use if (!$scope.names.find(function (name1) { $scope.names.push(name1); }) } Commented Oct 7, 2015 at 16:08
  • No, it's saying name1 isn't a function. Commented Oct 7, 2015 at 16:09
  • TypeError: name1 is not a function because .find takes a callback function and executes it on array items, and returns the value of an item that satisfies the callback function. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 7, 2015 at 16:10
  • 1
    @DaveNewton The error is self-explanatory, it says that the passed parameter is not a function, that means parameter should be a function Commented Oct 7, 2015 at 16:10
  • @Tushar Which is precisely what I said. Commented Oct 7, 2015 at 16:17

2 Answers 2

5

You need to use indexOf. Your snippet would be

if($scope.names.indexOf(name1) < 0) { //Value not exists in your array
   $scope.names.push(name1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

An index of zero means the element is at the zeroth position and therefore does exist in the array. You can instead do $scope.names.indexOf(name1) === -1.
Or $scope.names.includes(name1).
0

Alternatively, consider using underscore.js There are a lot of useful functions including _.find()

Comments

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.