# Flatten Array/Object

[Codepen](https://codepen.io/hannahpun/pen/MdEVER?editors=1010)

### Flatten one level array

```
/**
 * @param {number[]} arr
 * @return {number[]}
 */
var flatten = function(arr) {}
```

```
Example 1:

Input:  [1, 2, [5, 6]]
Output: [1, 2, 5, 6]
```

#### Solution 1

若是純數字就放進新 Array，若不是則在做一次

```

var flatten = function(arr) {
  let newArr = [];
  convert(arr);
  
  function convert(lists) {
    lists.forEach(list => {
      if( !Array.isArray(list) ){
        newArr.push(list)
      } else{
        convert(list);
      }
    })
   }
   
   return newArr;
}

console.log(flatten([1, 2, [5, 6, [7, 8]]]))
```

#### Solution 2

比較簡潔的做法，使用 reduce. previous 被我初始化會是 \[]

```
[].concat(1) // [1]
[1, 2].concat[3, 4] // [1, 2, 3, 4]
```

```
var flatten = (lists) => lists.reduce((previous, cur) => previous.concat(cur), [])
```

### Flatten multiple level array

```
/**
 * @param {[] || number[]} arr
 * @return {number[]}
 */
var flattenMultiple = function(arr) {}
```

```
Example 1:

Input – [ 2, 3 , [ 4, 5, 6, [ 7 ], 8 ], 9]  
Output – [ 2, 3, 4, 5, 6, 7, 8, 9 ]

Example 2:
Input  – [ 2, 3, 4, 5, [6] ]   
Output – [ 2, 3, 4, 5, 6 ]
```

### Flatten object

```
/**
 * @param {object} arr
 * @return {object}
 */
var flattenObj = function(arr) {}
```

```
Example 1:

Input
{
  name: "Vishal",
  address: {
    primary: {
      house: "109",
      street: {             
        main: "21",
        cross: "32"
      }
    }
  }
};
Output
{
  user_name: "Vishal",
  user_address_primary_house: "109",
  user_address_primary_street_main: "21",
  user_address_primary_street_cross: "32",
}

```

其實跟 Array 大同小異，只差在 key 的部分

```
let newObj = {};
var flatten = function(obj, keyName) {

  for(const [key, value] of Object.entries(obj)){
     if(typeof value !== 'object'){
       newObj[`${keyName}_${key}`] = value;
    } else{
      flatten(value, `${keyName}_${key}`);
    }
  }
  
  return newObj;

}

console.log(flatten(user, 'user'))
```

### DOM

```
let data = {
  "Fish": {
    "trout": {},
    "salmon": {}
  },

  "Tree": {
    "Huge": {
      "sequoia": {},
      "oak": {}
    },
    "Flowering": {
      "apple tree": {},
      "magnolia": {}
    }
  }
};
```

![](/files/ULvuZkeAUW1BTlVFRBWg)

```
function createTree (data) {
  
  
  function createTreeDOM( data){ 
    let ul = document.createElement('ul');
    
    
    if(!Object.keys(data).length) return '';

    for(const [key, value] of Object.entries(data)){
      let li = document.createElement('li');
      li.textContent = key;

      li.append(createTreeDOM(value))
      ul.append(li) 
    }   
    
    return ul;
    
  }
  container.append( createTreeDOM(data) )
 
  
}
print(input)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hannahpun.gitbook.io/leetcode-note/others/flatten-array-object.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
