falauthy
falauthy

Reputation: 681

Can't run simple code in console via node

I wrote simple code in JS

const a = [1, 2, [3, 4, [5, 6]]];

console.log(a.flat());

And I have error like this

console.log(a.flat());
          ^

TypeError: a.flat is not a function

I'm running code via node

node test.js

Do I need install some packages? I'm working on macOS.

Upvotes: 2

Views: 144

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44087

You most likely have an outdated version of Node.JS - as seen here, you need Node.JS 11 or newer.

Download the latest version of Node.JS from the website.

If you can't use/get the latest version, you could use the MDN polyfill which works for multiple levels of nesting:

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

Upvotes: 0

jsdeveloper
jsdeveloper

Reputation: 4045

Seems like Array.flat is not available in nodejs (v10).

Ah yes v11+ only - see compatability table: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

Upvotes: 1

Related Questions