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
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    Use Custom Missing Image Graphics Using MooTools

    Missing images on your website can make you or your business look completely amateur. Unfortunately sometimes an image gets deleted or corrupted without your knowledge. You'd agree with me that IE's default "red x" icon looks awful, so why not use your own missing image graphic? The MooTools JavaScript Note that...

  • By
    Introducing MooTools ScrollSide

    This post is a proof of concept post -- the functionality is yet to be perfected. Picture this: you've found yourself on a website that uses horizontal scrolling instead of vertical scrolling. It's an artistic site so you accept that the site scrolls left to right.

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!