https://www.wisdomgeek.com/development/flatten-arrays-in-vanilla-javascript-with-flat-and-flatmap/ * Home * Development * Self Help * About * Contact * Privacy Policy Sign in Welcome!Log into your account [ ]your username [ ]your password [LOG IN] Forgot your password? Privacy Policy Password recovery Recover your password [ ]your email [Send My Pass] Search [ ] WisdomGeek * Home * Development * Self Help * About * Contact * Privacy Policy WisdomGeek Facebook Instagram LinkedIn Twitter Youtube * Home * Development * Self Help * About * Contact * Privacy Policy More [ ] Search Flatten Arrays in Vanilla JavaScript with flat() and flatMap() [svg][e354decd32cf] By Saransh Kataria Modified date: January 5, 2022 Development ES2019 introduced two methods on the array prototype that would make life so much simpler for developers. These are flat() and flatmap() which help in flattening arrays. Array.prototype.flat() As the name suggests, the flat() method returns a new array with elements of the subarray flattened into it, that is the sub-elements are concatenated into a single array. - Advertisement - [INS::INS] [[1, 2], [3, 4], [5, 6]].flat(); // [1, 2, 3, 4, 5, 6] By default, it flattens only one level deep, but it does take a depth argument which can be used to specify how many levels of depth we want to flatten. const twoLevelsDeep = [[1, [2, 2], 1]]; // depth = 1 twoLevelsDeep.flat(); // [1, [2, 2], 1] // depth = 2 twoLevelsDeep.flat(2); // [1, 2, 2, 1] Note: Infinity is a valid value for the depth if we want it to go all the way down. Array.prototype.flatMap() flatMap is a smarter version of map, which does mapping of an array and flattening in one go. It does map() first, and then flat() even though that is not the order in the naming of the function. const newArray = arrayObject.flatMap(callback(currentValue, index, array) { ... }, thisArg); As can be seen, the flatMap method takes in a callback function and a reference to this as arguments. The thisArg is optional and is the value used for the "this" variable inside the callback. The callback function contains a reference to the current value and the index and array values are optional. The return value of the function is the flattened value of the array returned by the callback function. let array = [1, 2, 3, 4]; array.map(x => [x * 2]); // [[2], [4], [6], [8]] array.flatMap(x => [x * 2]); // [2, 4, 6, 8] // only one level is flattened array.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]] There is no way to specify the depth in a flatMap and it is set to 1 by default. It is also possible to add or remove elements when using flatMap() which is not a possibility using map(). If we wanted to remove all negative items from an array: const numbers = [-1, 2, 3, -4, 5]; numbers.flatMap(number => { return number < 0 ? [] : [number]; }); // [ 2, 3, 5] It can act as filter because of the empty array. const emptyNestedArray = [[], 1]; emptyNestedArray.flat(); // [ 1 ] Similarly, if we return an array with multiple elements from the callback, those would be added as individual items to the flattened array. For example, if we wanted to add a number's double and triple right after every element in an array: const numbers = [1, 2]; const appendedDoublesTriples = numbers.flatMap(number => { return [number, 2 * number, 3 * number]; }); console.log(appendedDoublesTriples); // logs [1, 2, 3, 2, 4, 6] And that is all there is to know about flat and flatMap(). Hope these were helpful and again, these were a part of ES2019, so we need to add polyfills if we are supporting browsers before that. * Tags * javascript Share Facebook Twitter Linkedin WhatsApp ReddIt Pinterest Email Previous articleUsing GroupBy on an array of objects in JavaScript Recent Articles Flatten Arrays in Vanilla JavaScript with flat() and flatMap() Development Saransh Kataria - Modified date: January 5, 2022 0 ES2019 introduced two methods on the array prototype that would make life so much simpler for developers. These are flat() and flatmap ()... Read more Using GroupBy on an array of objects in JavaScript JavaScript Saransh Kataria - Modified date: December 29, 2021 0 Array grouping is a fairly common operation in any project. Until recently, we had to resort to either writing our own implementation... Read more Node.js introduces node: protocol imports JavaScript Saransh Kataria - Modified date: December 23, 2021 0 Node.js recently introduced a node: protocol for built-in modules. Built-in node modules can now be imported by prefixing the node: protocol prefix. Read more 4 Tips To Maximize Your Productivity At Work Collaboration Saransh Kataria - Modified date: December 14, 2021 0 If you find yourself procrastinating because of the slightest distraction or don't have an organized system to manage your productivity, this article... Read more JSON Modules in JavaScript JavaScript Saransh Kataria - Modified date: December 8, 2021 0 ES Modules were introduced in ES2015. The import and export keywords by default are only applicable to JavaScript code. But there is... Read more Related Stories Development How to permanently remove a file from Git history Saransh Kataria - Modified date: November 12, 2021 0 We all make mistakes sometimes. Pushing files that contain some secrets or sensitive information to a Git repository is fairly common. And... Read more Development Opening a Browser with DevTools Open by Default Saransh Kataria - Modified date: December 7, 2021 0 While automating some parts of my development workflow, I was wondering if there was a way of opening a browser with DevTools... Read more Development Installing Intel-based packages using Homebrew on the M1 Mac Saransh Kataria - Modified date: March 3, 2021 2 I recently got the new Apple Silicon Mac (aka the M1 mac), and that means having to deal with the pain points... Read more Development Machine Learning Misconceptions That Software Developers Have Pranshu Aggarwal - Modified date: September 9, 2020 0 There has been a rapid advancement in technology and machine learning in the past decade. This has been accompanied by accelerated and... Read more Development Rest and Spread operator: Three dots that changed JavaScript Saransh Kataria - Modified date: October 17, 2019 0 The rest and spread operator have changed the way I do a lot of things in JavaScript and I have started using... Read more Leave A Reply Cancel reply [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Please enter your comment! [ ] Please enter your name here [ ] You have entered an incorrect email address! Please enter your email address here [ ] [ ] Save my name, email, and website in this browser for the next time I comment. [Post Comment] [gif][tdn_pic_3] Hi there! Want some more knowledge? Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out. [ ] Subscribe * Home * Development * Self Help * About * Contact * Privacy Policy (c) Wisdom Geek. All Rights Reserved. Close this module newsletternewsletter Hi there! Want some more knowledge? Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out. Enter your email[ ]Enter your email Sign me up! NO THANKS Add Wisdom Geek to your Homescreen! Add