I tend to generate a lookup dictionary as soon as I have the data. So in any case I only need to iterate the data once.
Comparing with your approach, let's say we need to call getByKey()
multiple times, the total cost of iterating the data might actually be higher.
I suppose which approach being more suitable really depends on your own application or design. But I also find myself sometimes generating different lookup dictionaries from the same set of data, and I would still only need to iterate the data once.
As for the .sort()
bonus question, I would say that in terms of readability and code maintenance, yes, I would consider it one of the best ways of sorting a json collection.
var data = [
{
"Key": "2222-2222-2222",
"Email": "[email protected]"
},
{
"Key": "1111-1111-1111",
"Email": "[email protected]"
}
],
lookup = {};
// generate the lookup table for reuse
data.forEach(function (el, i, arr) {
lookup[el.Key] = el.Email;
});
// should return '[email protected]'
console.log(lookup['1111-1111-1111']);
// sort by Key
var keys = data.sort(function (a, b) {
var c = a.Key,
d = b.Key;
return c > d ? 1 :
d < c ? -1 :
0;
});
console.log(keys[0].Key); // should return '1111-1111-1111'
// sort by Email
var emails = data.sort(function (a, b) {
var c = a.Email,
d = b.Email;
return c > d ? 1 :
d < c ? -1 :
0;
});
console.log(emails[0].Key); // should return '2222-2222-2222'