DEV Community

Jan Küster
Jan Küster

Posted on

JavaScript puzzle - get length of an Array without using length

Write a function fn that returns the length of an Array as Number.

Constraints:

  • no use of length property
  • size and length/size indicating properties of other data structures are also not allowed

Tips:

  • try to avoid the comments section, as the solutions are often posted there
  • it's way easier than you might think (which is why it's tagged #beginners)
  • read about Array fundamentals
  • don't expect the solution to be something that you should ever use in production code

Tests:

console.assert(fn([]) === 0)
console.assert(fn([1]) === 1)
console.assert(fn(['1']) === 1)
console.assert(fn(['1', 2, {}]) === 3)
Enter fullscreen mode Exit fullscreen mode

Bonus:

This is all achievable by using 20 characters (inkl. function declaration) overall.

Top comments (5)

Collapse
 
lexlohr profile image
Alex Lohr

Push returns the length; otherwise one could use recursion:

let l=a=>a.push()
// or recursive, but too long:
let l=(a,i=0)=>i in a?l(a,i+1):I
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devdufutur profile image
Rudy Nappée • Edited


const fn = arr => arr.reduce(acc => acc + 1, 0);

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

16 chars using push...
In my opinion, this is not a solution because push returns the new array length.
If I solve it recursively, the smallest variant is 26 chars long.
Therefore I would be interested in the 20 chars solution.

Collapse
 
jankapunkt profile image
Jan Küster

The puzzles are not looking for solutions, that are valid to be used in the real world (I should have mentioned that in the article). It's more intended to make people think out f the box and have a fun way to do some research about fundamental functionalities. From such a viewpoint, a push solution would be sufficient as it would comply with fn = Array => Number.

Collapse
 
kateshim625 profile image
kateshim625

Thank you for the info!