Skip to content

Instantly share code, notes, and snippets.

@GeekaholicLin
Created September 4, 2016 08:59
Show Gist options
  • Select an option

  • Save GeekaholicLin/0d905ca20b422c2e65e8b23a8881f1c3 to your computer and use it in GitHub Desktop.

Select an option

Save GeekaholicLin/0d905ca20b422c2e65e8b23a8881f1c3 to your computer and use it in GitHub Desktop.
数组扁平化

两级数组嵌套扁平化

Array.prototype.concat.apply([],array);

function flattern(arr){
  var myArray = Array.prototype.concat.apply([],arr);
console.log(myArray);
}
flattern([[1],[2,3],[4,5,6]]);//logs [1, 2, 3, 4, 5, 6]
flattern([[1],[2,3,[4,5,6]]]);//logs [1, 2, 3, [4, 5, 6]]

多级嵌套扁平化

function steamroller(arr) {

  var result = [];
  if(Array.isArray(arr)){
    for(var i = 0,length = arr.length;i<length;i++){
      result = result.concat(steamroller(arr[i]));
    }
  }else{
    result.push(arr);
  }
  return  result;
}
steamroller([[["a"]], [["b"]]]);//logs ["a", "b"]
steamroller([[1],[2,3,[4,5,6]]]);//logs [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment