Skip to content
Advertisement

Calculating the mode value of an array

The function for returning the mode value of an array works on every test except one. When I pass the following array through the function, I get a TypeError. I figured out that it has something to do with the number 0 in the passed array, but I don’t know why and I don’t know how to solve the problem. This is what my mode function and my typeerror function looks like.

JavaScript

If I pass [3, 5, 2, -5, 9, 2, -5, 5, 10, 4, 1, 0, -1, 9, 0] to the function, I get TypeError: “The passed array may only contain valid numbers”, but I expected to get [-5, 0, 2, 5, 9]

Advertisement

Answer

The callback function that you pass to Array.prototype.every() should return a boolean value. If it (the callback function) returns true for every element of array then only theevery method will return true.

Note this line in your callback :

JavaScript

You are returning element instead of boolean value. When the callback returns a 0 it is automatically casted to boolean false. and thus the every() returns false causing function to throw the TypeError.

Fix the callback :

JavaScript

Can be written as ES6 arrow function :

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement