Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.find(value) return value 'is not a function'

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().

like image 329
UltraSonja Avatar asked Oct 07 '15 16:10

UltraSonja


People also ask

What does array find return if not found?

JavaScript Array find() The find() method returns undefined if no elements are found.

Does array find return reference or copy?

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. Whether it returns a copy of or a reference to the value will follow normal JavaScript behaviour, i.e. it'll be a copy if it's a primitive, or a reference if it's a complex type.

Is it possible to find a variable is an array or not?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

Is not a function at array map?

The "TypeError: map is not a function" occurs when we call the map() method on an object that is not an array. To solve the error, console. log the value you're calling the map() method on and make sure to only call the map method on valid arrays.


1 Answers

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);
}
like image 141
Vineet Avatar answered Oct 09 '22 08:10

Vineet