Home > Mobile >  Non-anonymous named function to sort multidimensional object by SPECIFIED sub-key's value
Non-anonymous named function to sort multidimensional object by SPECIFIED sub-key's value

Time:03-29

I have an object (not an array):

var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};

Unlike this generic sorting question I need to specify which sub-key's value to sort by, in this case: date. For the sake of simplicity I've removed the first seven digits of the dates as that is not important.

After the sorting the object should be sorted by the values of the date key as follows:

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 need to create a reusable non-anonymous named function with two obvious parameters: the object and the key whose value the sorting is based on. I've been spending some time trying experimenting with the following without any success yet:

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 can not use o.sort as that is for array types (even though JavaScript claims that everything is an object and that "arrays" do not exist).
  • I can not overemphasize that I must be able to specify the name of the key as I need to use this form of sorting for a few different things. What I am missing here?
  • Absolutely no frameworks or libraries.

CodePudding user response:

How about convert object to array to sort and convert back?

var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};
console.log(Object.fromEntries(Object.entries(people).sort((a,b) => {
    return a[1].date - b[1].date
  })))

var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};
console.log(Object.fromEntries(Object.entries(people).sort(([,a],[,b]) => {
    return a.date - b.date
  })))

As a named function:

function array_sort_by_values(o, k)
{
 return Object.fromEntries(Object.entries(o).sort((a,b) => {return a[1][k] - b[1][k]}));
}

To keep the changes in effect the object has to be reassigned:

people = array_sort_by_values(people, 'date');
console.log(people);

array_sort_by_values(people, 'last')
console.log(people);
  • Related