Flatten Array/Object

for of 很好用,記得常用 for(const [key, value] of Object.entries(obj))

Codepen

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": {}
    }
  }
};
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)

Last updated