Irakli Berberashvili
Irakli Berberashvili

Reputation: 31

How to check if Strings are in array?

example:

var arr = ["a", "b", "c", "d", "e", "f"];

how to check if "a", "b" and "c" are in array?

i tried indexOf() but i cant check if more than 1 strings are in array...

Upvotes: 2

Views: 77

Answers (2)

Suchit kumar
Suchit kumar

Reputation: 11859

try like this:

var arr = ["a", "b", "c", "d", "e", "f"];
var arr1=['a','b','c'];
     for(i=0;i<arr1.length;i++){
         var a1 = arr.indexOf(arr1[i]);
            console.log(a1);
     }

or

var a = arr.indexOf("a");
console.log(a);//0
var b = arr.indexOf("b");
console.log(b);//1
var c = arr.indexOf("c");
console.log(c);//2

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

You are use Array.protoype.every and Array.prototype.indexOf, like this

["a", "b", "c"].every(function(currentItem) {
    return arr.indexOf(currentItem) !== -1;
});

This will return true, only if all the elements in ["a", "b", "c"] are present in arr.

Upvotes: 1

Related Questions