Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function for flatten a multi-dimensional array [duplicate]

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.
like image 810
Bacchus Avatar asked Sep 24 '26 21:09

Bacchus


2 Answers

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]
like image 87
maerics Avatar answered Sep 27 '26 12:09

maerics


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/

like image 23
VisioN Avatar answered Sep 27 '26 10:09

VisioN