DEV Community

loading...
Cover image for Javascript Interview Question: Select only the numbers in the array (with strange cases).

Javascript Interview Question: Select only the numbers in the array (with strange cases).

Lautaro Jayat
A curious geek. Keen at NodeJS, Golang and Linux.
・3 min read

In this article we will try to solve something that looks like a simple problem but can scale and become very strange deal. The problem is the following one:

let array = [1, 2, 3, '4', undefined, 'a', [], null];
Enter fullscreen mode Exit fullscreen mode

If you have an array make a function that returns other array wich contains only numbers. The array is the following one:

But now they change the question and says: “Oh! but could you please also include numbers that were written as strings, like '2' or '404'?

First we could tryisNaN() , because is a higher function built-in Javascript that can tell us if something is not a number. It returns true or false, and also evaluates strings of numbers as numbers.

So we try the following:

Ouch! We forgot that they are asking for an array of Numbers!
But… there is something more.

Curious, an empty array and null are both numbers.
It happens that Javascript is a Dynamic Type programing language so, different from C, the language has it’s own parser and protocols to know if a variable is a number, a string, and so on.

It seems that this behavior was intended that way so back in the 1995 the future developers of the newborn internet could applay their coding patterns (from a lot of different programing languages) into Javascript. But of course, no one could ever know that the community will push the language to the extreme.

If you want to know more about this weird behaivors, I recomend this excelent repository called “What the f*ck Javascript?”.

GitHub logo denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples

What the f*ck JavaScript?

WTFPL 2.0 NPM version Patreon Buy Me A Coffee

A list of funny and tricky JavaScript examples

JavaScript is a great language. It has a simple syntax, large ecosystem and, what is most important, a great community.

At the same time, we all know that JavaScript is quite a funny language with tricky parts. Some of them can quickly turn our everyday job into hell, and some of them can make us laugh out loud.

The original idea for WTFJS belongs to Brian Leroux. This list is highly inspired by his talk “WTFJS” at dotJS 2012:

dotJS 2012 - Brian Leroux - WTFJS

Node Packaged Manuscript

You can install this handbook using npm. Just run:

$ npm install -g wtfjs

You should be able to run wtfjs at the command line now. This will open the manual in your selected $PAGER. Otherwise, you may continue reading on here.

The source is available here: https://github.com/denysdovhan/wtfjs

Translations

Currently, there are…

So now that we know a little more about this, lets find a way to solve our original problem.

If you remember, the problem was that our function can’t distinguish between a number, null and an empty array.

One solution could be changin isNaN() to something that only works well with strings and numbers, like the function parseInt(string|number, base), another higher-order function tries to convert everithing into an integer.

So, if we arrange our code, it will look like this:

Although it would be a very strange scenario, this code will also work fine if we have the following arrays:

let array1 = [1, 1.2, "3", 0, "0x" undefined, []]
let array2 = ["undefined, null, NaN, "0f"]
LET ARRAY3 = [number.POSITIVE_INFINITY, true, false]
Enter fullscreen mode Exit fullscreen mode

But, now that we are talking about wierd cases, lets make this code fail.

The first case I could think is one in wich, for one reason, someone puts stufs like ["20x", "5f", "1f"]. For this cases, the code will output NaN for each element.

To solve this we first need to make sure that they are not asking us to parse numbers in hexadecimal (base 16), because in that case 20F is 527 base 10, and we would need to do a lot more of stuff that is out of the scope of this article.
Once we know that they are just looking for every number in our decimal world, we need change the expression that we are testing for the condition:
Instead of if (parseInt(e)){...} we need something like:

if (parseInt(e) && parseInt(e) !== NaN) {...}

Bonus tip:

Because beeing a Dynamic Typed language, Javascript has a lot of weird stuffs. One that could mess with this approach to the problem is the following:

let a = [true + true];
console.log(a[0].toString()) // Will Output '0';
console.log(isNaN(a[0]))     // Will Output False
console.log(true + true);    // Will Output 2
console.log(null + null);    // Will Output 0
console.log(typeof (a[0]));  // Will Output 'number'
Enter fullscreen mode Exit fullscreen mode

So in this case, if we had this array [false, true + true, false] our function will output [0].

It seems that there is no way in Javascript to distinguish expressions that are additions of booleans and numbers. But, to encounter with a problem in a Javascript job that requires to select only numbers in an array that also has operations with booleans and positive infinities seems a little unreal.

One could ask: how you guys end up with such weird looking way of storing all this heteroclite data?
Given this problem, the first meassure could be try to avoid repeating this problem by fixing the functions so we only have sets of data that we could easily manage… maybe this is why they invented Typescript.

Discussion (0)