Reputation: 39
This function is only returning true. I have added a console.log in the if block and it is called but the function doesn't return false.
function isUniform(List)
{
var ele = List[0];
List.forEach(function(item)
{
console.log(ele);
if(ele !== item)
{
return false;
}
})
return true;
}
Upvotes: 0
Views: 980
Reputation: 386520
You need another method for testing unifomity. Better use Array#every
, which checks every value with the first item of the array and return true
, if all elements are equal and false
if not. The iteration stops with the first unequal element.
function isUniform(list) {
return list.every(function(item, _, array) {
return item === array[0];
});
}
The used Array#forEach
returns always undefined
:
forEach()
executes the callback function once for each array element; unlikemap()
orreduce()
it always returns the valueundefined
and is not chainable.
Upvotes: 9
Reputation: 2672
I think you can use this code;
function isUniform(List)
{
var res = true;
var ele = List[0];
List.forEach(function(item)
{
console.log(ele);
if(ele !== item)
{
res = false;
return;
}
})
return res;
}
Upvotes: 0