A Map is similar to an object, but the key of a common object must be a string or a number. The key of a Map can be any data type. So how do you sort a Map object? Ah? Can you sort a Map? Look at the bai
Set an out-of-order Map object
const map = new Map(a)// I want to be out of order, how can you
map.set(2.'Lin Erxin')
map.set(1.'Lin Yixin')
map.set(5.'Five Hearts of Lin')
map.set(4.'Four Hearts of Lin')
map.set(3.'Lin SAN Xin')
console.log(map) / / Map {2 = > 'is not Lin, 1 = >' with Lin, 5 = > 'five heart Lin, 4 = >' Tudor Lin, 3 = > 'three heart Lin'}
Copy the code
Array.from (this method converts an array-like object or a traversable object into a real Array)
const map = new Map()
map.set(2.'Lin Erxin')
map.set(1.'Lin Yixin')
map.set(5.'Five Hearts of Lin')
map.set(4.'Four Hearts of Lin')
map.set(3.'Lin SAN Xin')
console.log(map) / / Map {2 = > 'is not Lin, 1 = >' with Lin, 5 = > 'five heart Lin, 4 = >' Tudor Lin, 3 = > 'three heart Lin'}
const arr = Array.from(map)
console.log(arr) / * [[2, 'Lin is not'], [1, 'Lin a heart], [5,' Lin five heart], [4, 'Lin Tudor'], [3, 'Lin three heart]] * /
Copy the code
Sorting (this article is just an example, it depends on what the arR looks like)
const map = new Map()
map.set(2.'Lin Erxin')
map.set(1.'Lin Yixin')
map.set(5.'Five Hearts of Lin')
map.set(4.'Four Hearts of Lin')
map.set(3.'Lin SAN Xin')
console.log(map) / / Map {2 = > 'is not Lin, 1 = >' with Lin, 5 = > 'five heart Lin, 4 = >' Tudor Lin, 3 = > 'three heart Lin'}
const arr = Array.from(map)
console.log(arr) / * [[2, 'Lin is not'], [1, 'Lin a heart], [5,' Lin five heart], [4, 'Lin Tudor'], [3, 'Lin three heart]] * /
arr.sort((a, b) = > a[0] - b[0])
console.log(arr) / * [[1, 'Lin a heart], [2,' Lin is not '], [3, 'Lin three heart], [4,' Lin Tudor '], [5, 'Lin five heart]] * /
Copy the code
Map([[a, b], [c, d]]) generates {a => b, c => d}Map object
const map = new Map()
map.set(2.'Lin Erxin')
map.set(1.'Lin Yixin')
map.set(5.'Five Hearts of Lin')
map.set(4.'Four Hearts of Lin')
map.set(3.'Lin SAN Xin')
console.log(map) / / Map {2 = > 'is not Lin, 1 = >' with Lin, 5 = > 'five heart Lin, 4 = >' Tudor Lin, 3 = > 'three heart Lin'}
const arr = Array.from(map)
console.log(arr) / * [[2, 'Lin is not'], [1, 'Lin a heart], [5,' Lin five heart], [4, 'Lin Tudor'], [3, 'Lin three heart]] * /
arr.sort((a, b) = > a[0] - b[0])
console.log(arr) / * [[1, 'Lin a heart], [2,' Lin is not '], [3, 'Lin three heart], [4,' Lin Tudor '], [5, 'Lin five heart]] * /
const map2 = new Map(arr) // Successful conversion
console.log(map2) / / Map {1 = > 'with Lin, 2 = >' is not Lin, 3 = > 'three heart Lin, 4 = >' Tudor Lin, 5 = > 'five heart Lin'}
Copy the code
Knowledge: Map object setup method, transformation method, and Array from method. Come on! You will have girlfriends!!