30

Is there a good way to check if all indexes in an array are strings?

check(["asd", 123]); // false
check(["asd", "dsa", "qwe"]); // true
4
  • @Compass All strings, even numeric. Commented Nov 11, 2014 at 17:49
  • 1
    stackoverflow.com/questions/4059147/… Tada Commented Nov 11, 2014 at 17:49
  • 1
    @Compass What do you mean, that's not the question? Commented Nov 11, 2014 at 17:50
  • @Murplyx If you have a concept of iteration and conditionals, knowing how to discern between a string and a number should be enough :) Commented Nov 11, 2014 at 17:51

4 Answers 4

67

You can use Array.every to check if all elements are strings.

const isStringsArray = arr => arr.every(i => typeof i === "string")

console.log( 
  isStringsArray(['a','b','c']),
  isStringsArray(['a','','c']),
  isStringsArray(['a', ,'c']),
  isStringsArray(['a', undefined,'c']),
  isStringsArray(['a','b',1]) 
)

Sign up to request clarification or add additional context in comments.

4 Comments

Just in case, IE>8 :)
In lodash, _.every(x, _.isString);
here is a solution with .some() which will prevent you from going through all elements function allElementsAreString(arr => !arr.some(element => typeof element !== "string")) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@MattCatellier: both some and every are "short circuiting", meaning that they will stop as soon as the condition is not satisfied for every or as soon as it is satisfied for some.
2

You could do something like this - iterate through the array and test if everything is a string or not.

function check(arr) {
 for(var i=0; i<arr.length; i++){
   if(typeof arr[i] != "string") {
      return false;
    }
 }

 return true;
}

Comments

0

Something like this?

var data = ["asd", 123];

function isAllString(data) {
    var stringCount;
    for (var i = 0; i <= data.length; i++) {
        if (typeof data[i] === 'string')
            stringCount++;
    }
    return (stringCount == data.length);
}

if (isAllString(data)) {
    alert('all string');
} else {
    alert('check failed');
}

1 Comment

@CambridgeMike version is far more efficient (:
0

My way:

check=function(a){
    for ( var i=0; i< a.length; i++ ) {
        if (typeof a[i] != "string")
            return false;
    };
    return true;
}
console.log(check(["asd","123"])); // returns true
console.log(check(["asd",123])); // returns false

Comments