user10516706
user10516706

Reputation:

JavaScript Array flat function doesn't define in React native

I'm writing an application based on react-native and we know definitely we can use JavaScript codes in this project and all react projects.

But when I use below code the transpiler return Error to the simulator:

const mixer = (...arg) => arg.flat(9);

The error is: flat is not function

Why in react-native it is not define but in browser works well?

Upvotes: 11

Views: 4541

Answers (4)

Wainage
Wainage

Reputation: 5412

React Native uses the JavaScriptCore engine which uses the ECMA-262 spec. The spec shows clearly that .flat is not supported and it is not included in the list of transformations for babel.

Write your own or install one of the many shims available on npm.

Upvotes: 5

KarelG
KarelG

Reputation: 5244

const mixer = (...arg) => arg.flat(9);

The error is: flat is not function

Why in react-native it is not define but in browser works well?

My first guess is that the react-native transpiler is not interpreting your ...arg correctly, leading to an object that is not of Array type. You are trying to call .flat, which is a part of Array.prototype. Since arg could not be of type Array, it is unable to find .flat, thus leading to that error.

I am not certain though. Can you check the object type? You can use this code here below temporarily.

const mixer = (...arg) => { console.log(typeof arg); return []; }

What does it say? If it says Array, then you might operate on a platform that does not support that function yet. Using a polyfill can solve your problem here.

Upvotes: 0

JGoodgive
JGoodgive

Reputation: 1126

Is it supported on your platform? Array.prototype.flat

Link also contains implementations using reduce and concat as well as non-recursive.

Upvotes: 0

Atishay Jain
Atishay Jain

Reputation: 1445

instead of arr.flat try using this function

function flatten(arr) {
    return Array.prototype.concat(...arr);
}

flatten(arr)

Upvotes: 0

Related Questions