Array.From

By  on  

In the past we used a variety of hacks to convert Array-like objects (like arguments and NodeList) to a true array.  You can see a few of those hacks here:

Essentially we would use Array.prototype.slice.call() on the arguments or NodeList to do the conversion.  These days there is a more straightforward solution to converting one type to another.

Convert NodeList to Array

var divs = Array.from(document.querySelectorAll('div'));

// Array[232] (every DIV on the page)

Convert arguments to Array

function something() {
  var args = Array.from(arguments);

  // Array['yes', 1, {}]
}
something('yes', 1, {});

Convert String to Array

Array.from('JavaScript'); // Same as 'JavaScript'.split('')

// ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]

The code is much cleaner and no need for the slice hack!

Recent Features

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • By
    NSFW Blocker Using MooTools and CSS

    One of my guilty pleasures is scoping out the latest celebrity gossip from PerezHilton.com, DListed.com, and JoBlo.com. Unfortunately, these sites occasionally post NSFW pictures which makes checking these sites on lunch a huge gamble -- a trip to HR's office could be just a click away. Since...

  • By
    Introducing MooTools ScrollSidebar

    How many times are you putting together a HTML navigation block or utility block of elements that you wish could be seen everywhere on a page? I've created a solution that will seamlessly allow you to do so: ScrollSidebar. ScrollSidebar allows you...

Discussion

  1. hexx

    small note -> babel doesn’t transpile Array.from() – so keep that in mind to include it ;)

    • hexx

      [].slice.call(stuff) isn’t much longer than Array.from(stuff)

    • XPoli

      Array.apply(0, stuff) is also a good solution

    • Prashant Palikhe

      It’s not about which one is shorter, Array.from is just more declarative approach to doing the same thing.

    • There’s a babel plug-in for Array.from()

      https://babeljs.io/docs/usage/polyfill/

  2. When using ES6, you can use the spread operator with array-like objects like this :

    const args = [...arguments];
    const nodes = [...document.querySelectorAll('div')];
    

    You can even use this with Sets, a cool trick to make an array unique :

    const myUniqueArray = [...new Set(myArray)];
    
  3. Instead of spread you could use rest operator:

    function something( ...args ) {
      // Array['yes', 1, {}]
    }
    something('yes', 1, {});
    
  4. Is the section “Convert String to Array” definitely correct?

    When I check the console I see the below:

    'JavaScript'.split('')
    Array [ "J", "a", "v", "a", "S", "c", "r", "i", "p", "t" ]
    Array.from('JavaScript');
    Array [ "JavaScript" ]
    
    • Espen

      That’s actually a bit funny. If you run that code in dev tools opened from this article, the Array.from function is overwritten by MooTools, and no longer works like the “native” version.

      Array.from = function(e) {
          return null  == e ? [] : o.isEnumerable(e) && "string" != typeof e ? "array" == t(e) ? e : s.call(e) : [e]
      }

      Run it in a new browser window and it should work.

    • Paul, did the same thing for me, but if I run the code somewhere else (tried it on repl.it) it works just as it’s supposed to.

  5. What he said…old MooTools has it wrong. I’ll be removing MooTools and all frameworks from the site soon.

  6. I built a site in reactjs with es6 recently. Standard stack (these days).
    The damn thing wouldn’t work on old Android browsers and certain browser in WebPageTest. “TypeError: function is undefined” (or something like that).

    Turns out these old browsers choked on the first occurrence of Array.from().

    Adding babel-polyfill made my day.

  7. Roni

    What about performance, which one is the best approach??

    • Eric Guittiere

      Looks like

      Array.prototype.slice.call(arraylike);

      is the fastest option (in Chrome and Firefox).

      [...arraylike]

      and

      Array.apply(0, arraylike);

      are second or third depending (different results in Chrome and FF), and unfortunately

      Array.from(arraylike);

      is the slowest by far on both browsers… :(

  8. Wanderson
    var a = Array.from({ length: 26 }, (a, i) => String.fromCharCode(97 + i));
    

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