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()
.
JavaScript Array find() The find() method returns undefined if no elements are found.
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.
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 .
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With