1

I'm currently stuck on a problem. I'm trying to make [[1,2,[3]],4] -> [1,2,3,4] but cannot get it to work. The output I keep getting is: 1,2,3,4 1,2,3 3 3 3 3..........3

function flattenArray(input) {
var result = [];
console.log(input.toString());
      for(i = 0; i < input.length; i++) {
           if(input[i].constructor === Array) {
           result.push(flattenArray(input[i]));
      } else {
           result.push(input[i]);
  }
}
    return result;
}

console.log(flattenArray([[1,2,[3]],4]));

1 Answer 1

1

I have this in my common.js file. I use it all the time.

Array.prototype.flatten = function () {
    var ret = [];
    for (var i = 0; i < this.length; i++) {
        if (Array.isArray(this[i])) {
            ret = ret.concat(this[i].flatten());
        } else {
            ret.push(this[i]);
        }
    }
    return ret;
};

Here it is as a function:

function flattenArray(input) {
    console.log(input.toString());
    var ret = [];
    for (var i = 0; i < input.length; i++) {
        if (Array.isArray(input[i])) {
            ret = ret.concat(flattenArray(input[i]));
         } else {
            ret.push(input[i]);
        }
    }
    return ret;
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.