11

is there an AngularJS way of checking if a value exists in an array

var array1 = ["a","b","c"]

i'm trying to do this..

var array2 = ["c", "d", "e"]

angular.forEach(array2, function (a) {
    if (a /*is NOT in array1*/) {
        array1.push(a);
    } else {
        return false
    }
});

3 Answers 3

29

You can use Array.indexOf which will return -1 if it's not found or the index of the value in the array.

So in your case:

if (array2.indexOf(a) < 0) {
  array1.push(a);
}
Sign up to request clarification or add additional context in comments.

Comments

10

You just need to use native Array.prototype.indexOf to check if value is in array or not:

var array2 = ["c", "d", "e"]

angular.forEach(array2, function (a) {
    if (array2.indexOf(a) === -1) {
        // a is NOT in array1
        array1.push(a);
    }
});

Comments

2

https://www.w3schools.com/jsref/jsref_includes_array.asp

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");

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.