Is there a good way to check if all items in an array are of the same type?
Something that does this:
[1, 2, 3, 4] // true
[2, 3, 4, "foo"] // false
Is there a good way to check if all items in an array are of the same type?
Something that does this:
[1, 2, 3, 4] // true
[2, 3, 4, "foo"] // false
Share
Improve this question
asked Mar 21, 2018 at 16:34
SachaSacha
89310 silver badges29 bronze badges
5 Answers
Reset to default 6You could create a Set from the types of each element in the array and make sure that it has at most one element:
console.log( allSameType( [1,2,3,4] ) );
console.log( allSameType( [2,3,4,"foo"] ) );
function allSameType( arr ) {
return new Set( arr.map( x => typeof x ) ).size <= 1;
}
You can use Array.every to check if all elements are strings.
arr.every( (val, i, arr) => typeof val === typeof arr[0]);
arr = ["foo", "bar", "baz"] // true
arr = [1, "foo", true] // false
Note:
arr = [] // true
Maybe less plicated solution would be
function sameTypes(arr, type) {
arr.forEach((item, index) => {
if (typeof item == type) {
console.log('TRUE');
} else {
console.log('FALSE');
}
});
}
Came up with a functional approach using recursion.
var array = [1, 2, "foo"]
function check([head, ...tail])
{
if(!head)
{
return true
}
else
{
var flag = true
tail.forEach(element => {
flag &= typeof element === typeof head
})
return flag? check(tail) : false
}
}
console.log(check(array))
Not exactly what OP asked but if you want to check if it's a certain type:
function isArrayOfType(arr, type) {
return arr.filter(i => typeof i === type).length === arr.length;
}
const numericArray = [1, 2, 3, 4, 5];
const mixedArray = [1, 2, 3, "foo"];
console.log(isArrayOfType(numericArray, 'number')); // true
console.log(isArrayOfType(numericArray, 'string')); // false
console.log(isArrayOfType(mixedArray, 'number')); // false