Order By

Benchmark created on


Preparation HTML

<script src = "https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js">
</script>

Setup

var r, _ = window._, lodash = window.lodash;

var nestedObj = [
 { id: '4', address: { zipCode: 4, streetName: 'Beta'}},
{ id: '3', address: { zipCode: 3, streetName: 'Alpha' } },
{ id: '1', address: { zipCode: 1, streetName: 'Alpha' } },
{ id: '2', address: { zipCode: 2, streetName: 'Alpha' } },
{ id: '5', address: { zipCode: 4, streetName: 'Alpha' } },
];

var objects = [
 { a: 'x', b: 3 },
 { a: 'y', b: 4 },
 { a: 'x', b: 1 },
 { a: 'y', b: 2 },
];

function sortBy( key, cb ) {
    if ( !cb ) cb = () => 0;
    return ( a, b ) => ( a[key] > b[key] ) ? 1 :
        ( ( b[key] > a[key] ) ? -1 : cb( a, b ) );
}

function sortByDesc( key, cb ) {
    if ( !cb ) cb = () => 0;
    return ( b, a ) => ( a[key] > b[key] ) ? 1 :
        ( ( b[key] > a[key] ) ? -1 : cb( b, a ) );
}

function orderBy( keys, orders ) {
    let cb = () => 0;
    keys.reverse();
    orders.reverse();
    for ( const [i, key] of keys.entries() ) {
        const order = orders[i];
        if ( order == 'asc' )
            cb = sortBy( key, cb );
        else if ( order == 'desc' )
            cb = sortByDesc( key, cb );
        else
            throw new Error( `Unsupported order "${order}"` );
    }
    return cb;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Native Orderby
objects.concat().sort(orderBy(['a'],['desc']));

ready
Lodash order By
_.orderBy(objects, 'a', 'desc');
ready
Lodash OrderBy Nested
_.orderBy(nestedObj,[['address', 'zipCode'],['address.streetName']],['asc', 'desc']);
ready
Native Nested Orderby
r = nestedObj.concat().sort( orderBy([['address', 'zipCode'],['address.streetName']],['asc', 'desc']));
ready

Revisions

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