how to flatten array in javascript using foreach loop
function flatten(arr) {
const result = []
arr.forEach((i) => {
if (Array.isArray(i)) {
result.push(...flatten(i))
} else {
result.push(i)
}
})
return result
}
// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Also in JavaScript:
- javascript dom cheat sheet
- js execute string
- beautify json python
- how to delete everything from a folder in js
- isDate javascript
- clearing cookie in js
- ternaire javascript
- javascript toFixed
- Find parent and child from array javascript
- javascript append to json
- two object combine together javascript
- change the color of toast toastr js
- javascript find child element
- how to get a toggle button to do different js functions
- ascii art christmas tree
- javascript closure inside loop
- document is not defined javascript in nuxt js
- js onclick open the phone application
- underscore js check boolean value
- Javascript convert html entity to string
- jspdf cdn
- how to draw flower petals around circle javascript
- jquery add remove class clicked element
- javascript sanitize input slug