2

May be this is a very simple question on this forum but I couldn't find the answer being novice to javascript. I have this following code in javascript -

Let map = new Map<String,String>
map.set('0', select)
map.set('1', "foo");
map.set('2', "bar");
map.set('3', "baz");

I want to sort this map based on value. But index 0 should be on top and others should be sorted. So the final output should be printed as below -

[{'0':'Select'},{'2':'bar'}, {'3':'baz'}, {'1': 'foo'}];

Could you please help me on this?

chikun
  • 199
  • 1
  • 15

1 Answers1

1

You could get the Map#entries of the map and sort the array.

To move a certain value to top (or keep this value at top), you need a return value for Array#sort which reflects the wanted order. In this case a is taken fom the conditions and if falsy, like zero, the second part after the logical OR || is taken.

let map = new Map();

map.set('0', "Select");
map.set('1', "foo");
map.set('2', "bar");
map.set('3', "baz");

result = Array.from(map).sort(([, a], [, b]) =>
    (b === 'Select') - (a === 'Select') || a.localeCompare(b)
);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks Nina .. I have accepted this answer. I have an entry in map as below - map.set('0',"Select") Is it possible to sort other entries and keep the select on top ? – chikun Oct 10 '20 at 16:21
  • you need a check for the top value and take the delta of the check. please see edit. – Nina Scholz Oct 10 '20 at 16:28
  • I am getting below error on (b === 'Select') - (a === 'Select') The left hand side of an arithmetic operation must be type 'any', 'number','bigint' or enum type – chikun Oct 10 '20 at 16:40
  • 1
    you could cast the values to number: `Number(b === 'Select') - Number(a === 'Select')` – Nina Scholz Oct 10 '20 at 16:43
  • Thank you so much :) Wish I could vote you more – chikun Oct 10 '20 at 16:45