Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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]
Comment

PREVIOUS NEXT
Code Example
Javascript :: bootstrap 4 open tab when opening modal 
Javascript :: switch new date getday javascript 
Javascript :: Array iteration in ES6 
Javascript :: remove last tag in dom javascript 
Javascript :: Add Text Inside Of React Component 
Javascript :: interactive svg javascript 
Javascript :: try catch 
Javascript :: express generator error handling 
Javascript :: angular 7 selected 
Javascript :: jquery parse html 
Javascript :: changing map style react-leaflet 
Javascript :: jquery fedein background color 
Javascript :: _.extend 
Javascript :: double ?? js 
Javascript :: send json file to kafka topic 
Javascript :: moment js date between two dates 
Javascript :: native module rnc_asyncsqlitedbstorage tried to override asyncstorage module 
Javascript :: javascript rest 
Javascript :: how to creacte react component 
Javascript :: jq storage object on refresh 
Javascript :: get last element in array javascript 
Javascript :: js export options 
Javascript :: how to change string to array in javascript 
Javascript :: find element in an array and replace it by a callback function 
Javascript :: variables dinamicas javascript 
Javascript :: how to use axios 
Javascript :: sequelize date format 
Javascript :: how to decode jwt token in react 
Javascript :: javascript save as pdf 
Javascript :: js include another 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =