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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.