I need to compare all values in ONE array to know if they're all equal or not. So this works fine and gives me the expected output
var myArray1 = [50, 50, 50, 50, 50]; // all values are same, should return true
var myArray2 = [50, 50, 50, 50, 51]; // last value differs, should return false
function compare(array) {
var isSame = true;
for(var i=0; i < array.length; i++) {
isSame = array[0] === array[i] ? true : false;
}
return isSame;
}
console.log('compare 1:', compare(myArray1)); // true
console.log('compare 2:', compare(myArray2)); // false
Then I've tried the same with reduce() but looks like I'm misunderstanding that function. They both say it is false. Am I doing something obviously wrong? Can I use reduce()
to get what I need? If so how?
var myArray1 = [50, 50, 50, 50, 50];
var myArray2 = [50, 50, 50, 50, 51];
console.log('reduce 1:', myArray1.reduce(
function(a, b){
return a === b ? true : false
}
));
console.log('reduce 2:', myArray2.reduce(
function(a, b){
return a === b ? true : false
}
));