Use Case Suggestion: How to Flatten array
See original GitHub issueUse Array.reduce() to get all elements inside the array and concat() to flatten them.
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
// flatten([1,[2],3,4]) -> [1,2,3,4]
Issue Analytics
- State:
- Created 6 years ago
- Comments:6 (6 by maintainers)
Top Results From Across the Web
11 Amazing Examples of JavaScript Flatten Array - eduCBA
Using flatMap(), It maps each value to a new value, and resulting array is flatten to a depty of maximum 1. ... flatMap()...
Read more >How to flatten nested array in javascript? - Stack Overflow
Conclusion: To flatten an arbitrarily nested array in a functional way we just need a one-liner: const flatten = f => traverse(f) (concat)...
Read more >How to Flatten a Nested Javascript Array | by Cynthia Okoliezeh
The flat() method has an optional argument known as depth (the number of levels to flatten the array) and returns a new array...
Read more >Flatten Arrays in Vanilla JavaScript with flat() and flatMap()
An overview of two new methods available on the Array prototype in JavaScript: flat and flatMap.
Read more >Flatten Array using Array.flat() in JavaScript - Samantha Ming
Here's the syntax for this method: array.flat(<depth>);.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
thanks to @elatfy & @kakadiadarpan 🎬 How to flatten a nested array in JavaScript
@kakadiadarpan yeah sure! Please keep it procedural style, similarly to all the use cases on codetogo, for example: How to convert from degree to radian in JavaScript rather than creating a reusable function, simply list the steps that alow you to transform the original input (in our case
[1, [2], 3, 4]
into a flattened array) Even though people will eventually use it as a function, the aim of codetogo is not to push people tocopy paste
code, we rather want them to learn, that’s why we list instructions step by step This is also a key differentiation between other awesome repos (such as https://github.com/Chalarangelo/30-seconds-of-code)Feel free to submit the PR even if you’re not 100% sure that it’s correct, I will help you with comments 😄 thanks for your time!