reduce vs compact

Benchmark created on


Preparation HTML


Setup

function compact(array) {
    let resIndex = 0;
    const result = [];

    if (array == null) {
        return result;
    }

    for (const value of array) {
        if (value) {
            result[resIndex++] = value;
        }
    }
    return result;
}
const array = Array(1000).fill(1);

Test runner

Ready to run.

Testing in
TestOps/sec
compact + map
const res = compact(array.map((val, idx) => idx % 2 ? undefined : val))
ready
reduce
const res = array.reduce((res, val, idx) => idx % 2 ? res : [...res, val], [])
ready

Revisions

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