Skip to main content
1 of 2
dijam
  • 311
  • 1
  • 10

Flattening array in Javascript

I have implemented a solution to flatten an array of multiple levels in Javascript. I am just a newbie so forgive any mistakes. Could someone give me any tips to improve the code?

function streamrollArray(arr) {
    var copyArr = arr;
    var to_return = [];

    while (true) {
        if (copyArr.length <= 0) { return to_return; }
        var head = copyArr[0];
        to_return = to_return.concat(getValues(head));
        copyArr = copyArr.splice(1);
    }
}

function getValues(arr) {
    var copyArr = arr;
    var to_return = [];

    if (!Array.isArray(arr)) {
        return arr;
    }

    while (true) {
        if (copyArr.length <= 0) { return to_return; }
        var head = copyArr[0];
        to_return = to_return.concat(getHead(head));
        copyArr = copyArr.slice(1);
    }
}

function getHead(head) {
    while (Array.isArray(head)) {
        head = head[0];
    }
    return head;
}
dijam
  • 311
  • 1
  • 10