We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
将多维数组转化为一维数组(类似_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); },[]); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
将多维数组转化为一维数组(类似_Underscore.js中的_flatten()函数)
如果仅是字符串数组 则可用
递归
利用reduce
The text was updated successfully, but these errors were encountered: