teddybear123
teddybear123

Reputation: 2424

How to check if value is in array with AngularJS

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

Upvotes: 11

Views: 62551

Answers (3)

Dujardin Emmanuel
Dujardin Emmanuel

Reputation: 106

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

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

Upvotes: 2

juco
juco

Reputation: 6342

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

Upvotes: 29

dfsq
dfsq

Reputation: 193301

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

Upvotes: 10

Related Questions