3
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
  1. I searched for some heliping function in "Professional JS for Web Developers" but I can't find one for finding the number of dimension of an array.
5
  • This is a great opportunity to learn recursion Commented Jun 25, 2014 at 16:29
  • just check if the inner element is an array Commented Jun 25, 2014 at 16:29
  • This is the answer I was looking at from that duplicate. Commented Jun 25, 2014 at 16:32
  • I'm not sure how you claim your 2nd test passed. Your function doesn't actually do anything other than take elements from one array and put them in another. Nothing is flattened. Your output is essentially identical to the input. Commented Jun 25, 2014 at 16:40
  • return [].concat.apply([], array); - was the solution. Thanks Andy for topic. Commented Jun 25, 2014 at 16:42

2 Answers 2

10

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]
Sign up to request clarification or add additional context in comments.

3 Comments

You should note that this code will work only in the newest browsers, that support Array.prototype.reduce and Array.isArray. Otherwise, polyfills must be applied.
@VisioN: indeed, I'm relying heavily on convenient, newer language features =)
this answer seams to be outdated: You can use the array.flat() function to flatten an array to any specific depth; Sorce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

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/

4 Comments

If you look at expected result #3, the intent isn't actually to fully flatten the array but rather just one level. [[[1,2,3]]] becomes [[1,2,3]] and not [1,2,3].
@JamesMontagne Not expected but excepted, which probably means the real results, which the OP received from his code, hence last "Test Failed".
Hah, I read that as expected, though I still assume that was what was intended as the results actually returned by the original code are just a copy of what was passed. The function does basically nothing.
@JamesMontagne Yeah, I know it's confusing, but I have just proposed another solution (apart from the ones in the related question), which seems to be doing what is expected :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.