Mowzer Mowzer - 1 year ago 130
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; });

Cheers

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