var flatten = function (array){
// TODO: Program me
var newArray = [];
for(var i = 0; i<array.length; i++) {
newArray.push(array[i]);
}
return newArray;
}
This are the results excepted:
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
The trick is that if an element of the input array is an array itself then you should "concat" the element's flattened items into the input array instead of pushing the entire array.
Here is a solution using "reduce" and "Array.isArray(...)" which are only available in newer browsers which support the later specification of ECMAScript 5.1th Edition:
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]
Here is one possible solution with using recursion:
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]
DEMO: http://jsfiddle.net/6ZhJ6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With