Flatten Array

JavaScript performance comparison

Test case created by Gaurav Nanda

Preparation code

<script>
   function flattenArrayWR(array) {
    var clonedArray = array.slice(0);
    var flattenedArray = [];

    while(clonedArray.length) {
        var item = clonedArray.shift();

        if (item instanceof Array === true) {
            clonedArray = item.concat(clonedArray);
        } else {
            flattenedArray.push(item);
        }
    }

    return flattenedArray;
}

function flattenArray(array, result) {
    result = result || [];
    for (var i = 0; i < array.length; i++) {
        if (Array.isArray(array[i])) {
            flattenArray(array[i], result);
        } else {
            result.push(array[i]);
        }
    }

    return result;
}
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Non Recursive
flattenArrayWR([1, 2, 3, [[4]], [[[5]]], [6], [[7]]])
pending…
Recursive
flattenArray([1, 2, 3, [[4]], [[[5]]], [6], [[7]]])
pending…

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments