I'm looking to compare all values within a single array to determine if they are all equal or not. My current method is working correctly and providing the expected result.
var myArray1 = [50, 50, 50, 50, 50]; // all values are the 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
However, when I attempted the same comparison using reduce(), I seem to be misunderstanding how that function works. Both instances return false. Is there an obvious mistake in my approach? Can reduce()
be used to achieve the desired result? If so, how should it be implemented?
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
}
));