Skip to content

Instantly share code, notes, and snippets.

@samgiles
Created June 20, 2014 11:32
Show Gist options
  • Star 88 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save samgiles/762ee337dff48623e729 to your computer and use it in GitHub Desktop.
Save samgiles/762ee337dff48623e729 to your computer and use it in GitHub Desktop.
Javascript flatMap implementation
// [B](f: (A) ⇒ [B]): [B] ; Although the types in the arrays aren't strict (:
Array.prototype.flatMap = function(lambda) {
return Array.prototype.concat.apply([], this.map(lambda));
};
Copy link

ghost commented Feb 3, 2021

/*
recursive methods (at least obvious ones) are for chumps! lets do some string manipulation instead...  
works, assuming your array does not actually includes "[" or "]" characters ¯\(◉◡◔)/¯
*/

Array.prototype.cheeky_flatMap = function(){
  return JSON.parse( "[" 
                   + JSON.stringify(this)
                         .replace(/[\[\]\,]+/g,",")
                         .replace(/(^\,|\,$)/g,"")
                   + "]"
                   );
}

Also, works in any depth...
cheeky_flatmap([[1,2],[3,4],[[[5]]]]) - [1,2,3,4,5]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment