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
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    Facebook-Style Modal Box Using MooTools

    In my oh-so-humble opinion, Facebook's Modal box is the best modal box around. It's lightweight, subtle, and very stylish. I've taken Facebook's imagery and CSS and combined it with MooTools' awesome functionality to duplicate the effect. The Imagery Facebook uses a funky sprite for their modal...

  • By
    Create Keyboard Shortcuts with Mousetrap

    Some of the finest parts of web apps are hidden in the little things.  These "small details" can often add up to big, big gains.  One of those small gains can be found in keyboard shortcuts.  Awesome web apps like Gmail and GitHub use loads of...

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!