28

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 Answers4

64

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]) 
)
vsync
  • 118,978
  • 58
  • 307
  • 400
6502
  • 112,025
  • 15
  • 165
  • 265
  • Just in case, IE>8 :) – nicosantangelo Nov 11 '14 at 17:52
  • 6
    In lodash, `_.every(x, _.isString);` – user3437231 Oct 31 '18 at 15:36
  • 1
    here is a solution with .some() which will prevent you from going through all elements `function allElementsAreString(arr => !arr.some(element => typeof element !== "string"))` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some – Matt Catellier Jul 30 '20 at 18:13
  • 3
    @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`. – 6502 Jul 30 '20 at 18:41
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;
}
CambridgeMike
  • 4,562
  • 1
  • 28
  • 37
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');
}
Latheesan
  • 23,247
  • 32
  • 107
  • 201
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
ton
  • 3,827
  • 1
  • 42
  • 40