var flatten = function (array){
// TODO: Program me
var newArray = [];
for(var i = 0; i<array.length; i++) {
newArray.push(array[i]);
}
return newArray;
}
这是结果除外:
flatten([1,2,3]) // => [1,2,3]
flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3]
flatten([[[1,2,3]]]) // => [[1,2,3]]
Test result:
Test Passed
Test Passed
Test Failed: Value is not what was expected
答案 0 :(得分:7)
诀窍是如果输入数组的一个元素本身就是一个数组,那么你应该将元素的扁平项"concat"放入输入数组而不是推送整个数组。
这是一个使用&#34; reduce&#34;的解决方案。和#34; Array.isArray(...)&#34;仅适用于支持ECMAScript第5.1版后期规范的较新浏览器:
function flatten(array) {
return array.reduce(function(memo, el) {
var items = Array.isArray(el) ? flatten(el) : [el];
return memo.concat(items);
}, []);
}
flatten([1,2,3]) // => [1,2,3]
flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3]
flatten([[[1,2,3]]]) // => [1, 2, 3]
答案 1 :(得分:1)
以下是使用递归的一种可能解决方案:
function flatten(array, result) {
result === undefined && (result = []);
for (var i = 0, len = array.length; i < len; i++) {
if (Object.prototype.toString.call(array[i]) === '[object Array]') {
flatten(array[i], result);
} else {
result.push(array[i]);
}
}
return result;
}
flatten([1,2,3]);
// [1, 2, 3]
flatten([[1,2,3], ["a","b","c"], [1,2,3]]);
// [1, 2, 3, "a", "b", "c", 1, 2, 3]
flatten([[[1,2,3]]]);
// [1, 2, 3]