What are the most efficient way to convert an HTMLCollection to an Array ?

What are the most efficient way to convert an HTMLCollection to an Array ?

Asked on December 18, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

    Try this solution:

    var arr = Array.prototype.slice.call( htmlCollection )
    

    Considering, the  expression is adequatly  equivalent:

    var arr = [].slice.call(htmlCollection);
    

    Here is the solution:

    var arr = Array.from(htmlCollection);
    

    According to ECMAScript 2015   provides the spread operator, which is fractionaly equivalent to Array.from .

    var arr = [...htmlCollection];
    

    The above work accomodate  on NodeList.

    Answered on December 18, 2018.
    Add Comment

    The succinct  ES6 syntax might be:

    let arry = [...htmlCollection]
    

    Try this code:

    let arry = Array.from(htmlCollection)
    
    Answered on December 18, 2018.
    Add Comment

    This method of getting Array.prototype to  Convert an HTMLCollection object into an Array object is determined here:

    [].slice.call( yourHTMLCollectionObject );
    

    Using this  compatibility function:

    function toArray(x) {
         for(var i = 0, a = []; i < x.length; i++)
            a.push(x[i]);
     
         return a
    }
    
    Answered on December 18, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.