vmwgeek
vmwgeek

Reputation: 87

Sorting map where value is an object with multiple values

I initialized the map like:

var map = new Map();

when i do console.log(map), i get:

testCreateBadAppointmentRequest: 
   { name: 'testCreateBadAppointmentRequest',
     time: 0.02926,
     status: 'Passed' },
  testAppointmentRequestAPI: 
   { name: 'testAppointmentRequestAPI',
     time: 0.051030000000000006,
     status: 'Passed' },

I want to sort this map on the time attribute of the value. How do i do that in nodejs? Is there a ready sort function to do so?

Upvotes: 0

Views: 168

Answers (3)

Carloluis
Carloluis

Reputation: 4320

Map order is determined by insertion order.

It should be noted that a Map which is a map of an object, especially a dictionary of dictionaries, will only map to the object's insertion order—which is random and not ordered.

Convert map to array with Array.from or using the spread operator on the map iterable. Then sort the array:

const map = new Map()
map.set('testCreateBadAppointmentRequest', { name: 'testCreateBadAppointmentRequest', time: 0.02926, status: 'Passed' });
map.set('testAppointmentRequestAPI', { name: 'testAppointmentRequestAPI', time: 0.051030000000000006,  status: 'Passed' });

// convert map to array
console.log('array', [...map.entries()]);
const array = Array.from(map);

// sort (inverse sort to change your current sort)
array.sort((x, y) => y[1].time - x[1].time);
console.log('sorted', array);

// create new map with objects pairs in the desired order:
const timeSortedMap = new Map(array);
console.log('sorted map', [...timeSortedMap]);

Upvotes: 1

charmeleon
charmeleon

Reputation: 2755

You will need to convert the Map to an Array first then use the built-in sort and provide a callback:

const sorted = Array.from(map).sort(function(a, b) {
    if (a.time < b.time) return -1;
    if (a.time > b.time) return 1;
    return 0;
});

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370779

You'll have to create a new Map object, since a Map object iterates its elements in insertion order.

    const inputMap = new Map(
      [
        ['testCreateBadAppointmentRequest',
          {
            name: 'testCreateBadAppointmentRequest',
            time: 0.02926,
            status: 'Passed'
          }
        ],
        ['testAppointmentRequestAPI',
          {
            name: 'testAppointmentRequestAPI',
            time: 0.051030000000000006,
            status: 'Passed'
          },
        ],
        ['another',
          {
            name: 'name',
            time: 0.0001,
            status: 'Passed'
          },
        ]
      ]);

    const sortedMap = new Map([...inputMap.entries()].sort((entryA, entryB) => entryB[1].time - entryA[1].time));
for (const value of sortedMap.values()) {
  console.log(value)
}

Upvotes: 0

Related Questions