Type Conversion with JavaScript Arrays

By  on  

JavaScript's loose nature allows developers to employ amazing tricks to do just about anything you'd like. I've detailed how you can filter falsy values in arrays using a filter(Boolean) trick, but reader David Hibshman shared another trick for typecasting array values the same way.

To typecast an array of elements, you can use map and the desired return type:

["1", "9", "-9", "0.003", "yes"].map(Number);
// [1, 9, -9, 0.003, NaN]

I love this trick but you could argue the code itself could be considered confusing, so wrapping it a helper function would be helpful:

function arrToNumber(arr) {
  return arr.map(Number).filter(Boolean);
}

Validation could and should probably be more rigorous but basic validation through typecasting might help you!

Recent Features

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

Incredible Demos

  • By
    Ana Tudor’s Favorite CodePen Demos

    Cocoon I love canvas, I love interactive demos and I don't think I have ever been more impressed by somebody's work than when I discovered what Tiffany Rayside has created on CodePen. So I had to start off with one of her interactive canvas pens, even though...

  • By
    CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

Discussion

  1. jzrskc
    ["0", "9", "-9", "0.003", "yes", true, false, undefined, null].map(Number);
    // [0, 9, -9, 0.003, NaN, 1, 0, NaN, 0]
    
    ["0", "9", "-9", "0.003", "yes", true, false, undefined, null].map(parseFloat)
    // [0, 9, -9, 0.003, NaN, NaN, NaN, NaN, NaN]
    
  2. MKM

    The .filter(Boolean) part also sees the zeros as booleans and removes those numbers.

  3. BryanYang

    very useful!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!