Javascript exercise that looks fine to me but its not working

Viewed 98

The exercise is about identifying if all elements in an array are the same and return true if they are or false if they aren't. Below is the code & my logic behind writing the code.

function isUniform(array){
  for(var i = array.length - 1; i>=0; i--){
    if(array[i] !== array[i-1]){
        return false;
    }
  }
  return true;
}

Basically I want to start from the end of the array with the last element and check if its equal with the second-to-last element.If they're equal, the loop will subtract 1 from the "i" variable and the "if statement" will run again. The loop will stop when i reaches -1 and thats the point where every array element was checked and the loop should end, returning true. What am I doing / thinking wrong?

Thanks!

4 Answers

When i becomes 0, you are comparing arr[0] with arr[-1] which is wrong. Your checking condition should be i > 0.

The very last time it run, i is 0, so you're comparing array[0] with array[-1] which is incorrect. Your Boolean condition should be i > 0 so you avoid this issue:

function isUniform(array){
  for(var i = array.length - 1; i > 0; i--){
    if(array[i] !== array[i-1]){
      return false;
    }
  }
  return true;
}

You can use every method for a simplified solution.

const allEqual = arr => arr.every(x => arr[0] == x));

You could create a method that checks the array for your input using ArrayUtils.

public boolean contains(final int[] array, final int key) {     
    return ArrayUtils.contains(array, key);
}

Traveling so can't debug, but the last iteration of i will be 0 in your code and stop.

Related