Mowzer Mowzer - 11 months ago 117
Javascript Question

Getting key of _.orderBy result in Lodash

I want to return the key of the first object returned by the

_.orderBy()
method which sorts by a nested property.

Here is the CodePen demo. In this case, the key I want to return is
"charlie"
.

console.clear();

const ob = {
"alpha": {
"id": 27,
"lottery": {
"id": 1,
"name": "La Primitiva",
"jackpotAmount": 500,
}
},
"bravo": {
"id": 28,
"lottery": {
"id": 1,
"name": "La Primitiva",
"jackpotAmount": 10,
}
},
"charlie": {
"id": 29,
"lottery": {
"id": 1,
"name": "La Primitiva",
"jackpotAmount": 1000,
}
},
}

const out = _.orderBy(ob, (e) => {
return e.lottery.jackpotAmount;
}, ['desc'] ); // How do I get key of first property, "charlie"?

console.log(out);

Answer Source

This isn't the most efficient way of getting the highest jackpotAmount. Sorting is O(n log n ). You can find the highest value in O(n) time. This is also creating a temporary copy of the list so it uses a lot of extra memory for a temporary operation. Using _.maxBy() would be more efficient.

var x = _.maxBy(ob, (e) => { return e.lottery.jackpotAmount; });
return x.id;

These functions work on lists. To get the key rather than item, you need to iterate over the keys.

var keys = Object.keys(ob);
return _.maxBy(keys, (e) => { return ob[e].lottery.jackpotAmount; });

Note that this doesn't entirely solve the efficiency issues. Depending on the javascript engine, the overhead of needing the keys array and the ob[e] lookup degrade space usage to O(n) and potentially a complexity of O(n log n).

If you're targeting a modern JS engine, you can use the Map object with a hand-written search to get constant space and linear time search.

const getMax = function (map) {
    let maxValue = null;
    let maxKey = null;

    map.forEach((value, key) => {
        if (value.lottery.jackpotAmount > maxValue) {
            maxValue = value.lottery.jackpotAmount;
            maxKey = key;
        }
    });

    return maxKey;
};

Here's a Codepen demo.

Cheers

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download