Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript reduce() – why is this returning false?

Basically, I want to evaluate all items in an array. If every item is of equal type AND value (strict equality check) return true, otherwise return false.
What am I missing here? – Thanks!

function equalityChecker(arr) {
  return arr.reduce((prev, curr) => {
    if (prev !== curr) {
      return false;
    } 
    if (prev === curr) {
      return true;
    }
  });
}

console.log(equalityChecker([0,0,0,0,0,0])); //returns false
console.log(equalityChecker([1,1,1,1,1,1])); //returns false

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array#reduce returns a value, and you return the result of a comparison.

In the next iteration, you use this boolean value and checks againsta value from the array.

Hint 1: Reduce does not work for this approach.

The other diadvantage is the iteration length, it loops for all elements despite a false value.

Hint 2: You need a method which returns early.

Result: Take Array#every and compare each element with the first item.

function equalityChecker(array) {
    return array.every((value, _, [first]) => first === value);
}

console.log(equalityChecker([0, 0, 0, 0, 0, 0])); //  true
console.log(equalityChecker([1, 1, 1, 1, 1, 1])); //  true
console.log(equalityChecker([0, 0, 0, 1, 0, 0])); // false
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading