Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组扁平化 #2

Open
LiuL0703 opened this issue Jan 2, 2018 · 0 comments
Open

数组扁平化 #2

LiuL0703 opened this issue Jan 2, 2018 · 0 comments

Comments

@LiuL0703
Copy link
Owner

LiuL0703 commented Jan 2, 2018

将多维数组转化为一维数组(类似_Underscore.js中的_flatten()函数)

var flatten = function(arr) {
    var res = [], idx = 0, val;
    for (var i =  0, length = arr && arr.length; i < length; i++) {
      val = arr[i];
      if (val && val.length >= 0 && Array.isArray(val)) {
        val= flatten(val);
        var j = 0, len = val.length;
        res.length += len;
        while (j < len) {
          res[idx++] = val[j++];
        }
      } else {
        res[idx++] = val;
      }
    }
    return res;
  }

flatten([1, [2], [3, [[4]]]])   //[1,2,3,4]

如果仅是字符串数组 则可用

arr = arr.join(",").split(",")
["1", ["2"], ["3", [["4"]]]].join(",").split(",")         //  ["1", "2", "3", "4"]

递归

function flatten(arr){
    var res = [];
    for(var i=0;i<arr.length;i++){
        if(Array.isArray(arr[i])){
            res = res.concat(flatten(arr[i]));
        }else{
            res.push(arr[i]);
        }
    }
    return res;
}

利用reduce

function flatten(arr){
    return arr.reduce(function(prev,item){
        return prev.concat(Array.isArray(item)?flatten(item):item);
    },[]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant