Sort a Map

I. Problem

Given a map, whose key are integer, sort map entries by the order of its key

1
2
3
4
5
6
7
8
9
10
11
12
13
Map:[
[2, 'c'],
[1, 'a'],
[4, 'a'],
[3, 'e'],
]

res: [
[1, 'a'],
[2, 'c'],
[3, 'e'],
[4, 'a'],
]

II. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
// Test
let map = new Map([[2, 'c'], [1, 'a'], [4, 'a'], [3, 'e']])

function sortMap(map){
let resKey = []
map.forEach((val, key)=>{
resKey.push(key)
})
resKey.sort()
return resKey.map(item=> [item, map.get(item)])
}

console.log(sortMap(map))

III. Complexity

  1. Time: O(N*logN)
  2. Space: O(N)