Search code examples
javascriptarraysnode.jsflattenflat

Array.prototype.flat() is not working in command line using Node JS


I am trying to test the array.flat method inside Visual Studio code using node js from the command line. When I run the code i get:

"TypeError: arr.flat is not a function"

I have ran the code in chrome and am able to get the desired result (a flattened array)

Note: Even after updating node js to the latest version, it is still not working.

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
console.log(arr1)


Solution

  • Only NodeJS version 11 and above support this method. Please note that the current LTS Node version is only at 10.16.3, which does not support this.

    Check the compatibility table.

    To check what version use this:

    node --version
    

    If you Node version is below 11, you will need to upgrade it to use it.

    Note

    Node versions that use odd number major versions (i.e., v11.x.x, v13.x.x) are generally perceived as a test version and should not be used for production applications. Use even number major versions (i.e., v10.x.x, v12.x.x) instead.