Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.flat() is not a function, what's wrong?

The following code

function steamrollArray(arr) {   // I'm a steamroller, baby   return arr.flat(); }  steamrollArray([1, [2], [3, [[4]]]]); 

returns

arr.flat is not a function

I tried it in Firefox and Chrome v67 and the same result has happened.

What's wrong?

like image 853
TechnoKnight Avatar asked Jun 22 '18 18:06

TechnoKnight


People also ask

What is a flat () in react?

Flat() This array method takes a single optional “depth” argument (which defaults to 1 should it be undefined ). It creates a new array with all sub-array elements concatenated into it recursively up to the value of 'depth'.


1 Answers

The flat method is not yet implemented in common browsers (only Chrome v69, Firefox Nightly and Opera 56). It’s an experimental feature. Therefore you cannot use it yet.

You may want to have your own flat function instead:

Object.defineProperty(Array.prototype, 'flat', {      value: function(depth = 1) {        return this.reduce(function (flat, toFlatten) {          return flat.concat((Array.isArray(toFlatten) && (depth>1)) ? toFlatten.flat(depth-1) : toFlatten);        }, []);      }  });    console.log(    [1, [2], [3, [[4]]]].flat(2)  );

The code was taken from here by Noah Freitas originally implemented to flatten the array with no depth specified.

like image 167
Ivan Avatar answered Sep 20 '22 12:09

Ivan