最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if all values of array are of the same type - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 6

You 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

发布评论

评论列表(0)

  1. 暂无评论