My data consists of a collection of objects, not an array:
var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};
In contrast to a general sorting question, I need to specifically indicate which sub-key's value should be used for sorting, in this case: date
. To simplify matters, I've omitted the first seven digits of the dates as they are irrelevant.
Once sorted, the object should arrange its elements based on the values of the date
key like so:
people['Jen'] = {date: 147, last: 'Roberts'}; // 147 is the lowest/first value
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'}; // 947 is the highest/last value
I am aiming to create a named, non-anonymous function that can be reused, requiring two obvious parameters: the object
and the key
by which the sorting will be done. Despite several attempts, the following approach has not yet yielded successful results:
function array_sort_by_values(o, k)
{
return Object.entries(o).sort().reduce(function (result, key)
{
//console.log(result,key);
result[key][k] = o[key][k]; return result;
}, {});
}
- I cannot utilize
o.sort
since it pertains to arrays rather than objects, despite JavaScript asserting that everything is an object without true "arrays". - The ability to specify the key name is crucial for me due to its use across different scenarios where sorting is needed. What aspect am I overlooking in my implementation?
- No external frameworks or libraries are acceptable in this solution.