Reputation:
I want to check if the array has similar elements or not.
If all elements are similar then return true else return false.
function isUniform(arr){
var first = arr[0];
for(var q=1; q < arr.length; q++){
if(arr[q]!==first){
return false;
}
}
return true;
}
The for loop is only checking the first two elements in the array and the rest are not being checked.
Why is this happening?
As you can see the first two arrays should have false output but the first two elements are same so it shows true. This means it is not checking the rest of the elements.
Upvotes: 1
Views: 759
Reputation: 2865
I just pasted your code into the developer console and it appears to be working. Because you have coded return false
when the elements are not equal, the function will stop. You could instead set a variable and return it at the end of the function.
function isUniform(arr){
var first = arr[0];
var result = true;
for(var q=1; q < arr.length; q++){
if(arr[q] !== first){
result = false;
}
}
return result;
}
The simple solution will have a runtime of O(n)
. So it's not necessarily great. But we can improve it! By adding in a simple break
we improve the efficiency of our algorithm! As soon as we encounter a value that doesn't equal our first value, we stop iterating and return our result. This is concept known as short-circuiting. It's somewhat similar to your original function, because it will not check all values in the array. However, with very large arrays this would be the preferred approach.
function isUniform(arr){
var first = arr[0];
var result = true;
for(var q=1; q < arr.length; q++){
if(arr[q] !== first){
result = false;
break;
}
}
return result;
}
You could also do some cool stuff using Set. Sets are meant to hold unique values. So, if we create a set and it's size is 1, we know that all our values are identical. If the size is greater than 1, there are at least Set.size
number of unique values in our array.
In the function below, we create a new Set from our array. We then use the size property on the Set object to check our condition! Clean and simple.
function isUniform(arr) {
return new Set(arr).size === 1;
}
Note: For very large arrays this is not efficient; it has a runtime of O(n)
Upvotes: 2