Search code examples
javascriptarraysstringtypeof

How to make this function check if elements in array(table1) are the same ? It works with numbers but not strings


Function is checking if elements inside array are the same

function isUniform(){
var table1 = ['a','b','a','a'];
for(var y = table1.length - 1; y>=0; y--){
    if( (typeof table1 === 'string' && table1[y] !== table1[y - 1]) || (typeof table1 !== 'string' && table1[y] !== table1[y - 1] && table1[y - 1] >0) ){
        return false;
    }
}
return true;}

it should return false

edit: thanks everyone for help !


Solution

  • you are checking the element at index y-1 is greater than 0. You should check of for the index not element at that index.

    function isUniform(table1){
      for(var y = table1.length - 1; y>=0; y--){
        if( (typeof table1 === 'string' && table1[y] !== table1[y -   1]) || (typeof table1 !== 'string' && table1[y] !== table1[y  - 1] && y - 1 > 0) ){
            return false;
        }
      }
    return true;
    }
    console.log(isUniform(['a','b','a','a']))

    Using Set()

    A simpler way to do that is using Set()

    const allEqual = arr => new Set(arr).size === 1 
    console.log(allEqual(['a','b','a','a']))

    Using every()

    You can also use every() and compare each element with first one.

    const allEqual = arr => arr.every(x => arr[0] === x);
    console.log(allEqual(['a','b','a','a']))

    Note: A function like this usually takes a parameter and then return based on that input. You are are not supposed to declare a local array and then only test on it.

    Secondly I couldnot understand the reason for typeof table1 === 'string'. If you would explain what are other requirements of function you will get a better solution.