如何对地图的值进行排序?

3 dart

有人能给我一个暗示吗?我想按列表的长度对地图的值进行排序.

var chordtypes = {
  "maj": [0, 4, 7],
  "M7": [0, 4, 7, 11],
  "m7": [0, 3, 7, 10],
  "6": [0, 4, 7, 9],
  "9": [0, 4, 7, 10, 14],
  "sus2": [0, 2, 7],
  "sus4": [0, 5, 7],
  "omit3": [0, 7],
  "#5": [0, 4, 8],
  "+7b9#11": [0, 4, 8, 10, 13, 18],
  "+9": [0, 4, 8, 10, 14]
};
Run Code Online (Sandbox Code Playgroud)

Gam*_*ist 7

一种函数,用于对List的Map进行排序.

import 'dart:collection';

/// sorts the ListMap (== A Map of List<V>) on the length
/// of the List values.
LinkedHashMap sortListMap(LinkedHashMap map) {
    List mapKeys = map.keys.toList(growable : false);
    mapKeys.sort((k1, k2) => map[k1].length - map[k2].length);
    LinkedHashMap resMap = new LinkedHashMap();
    mapKeys.forEach((k1) { resMap[k1] = map[k1] ; }) ;        
    return resMap;
}
Run Code Online (Sandbox Code Playgroud)

结果:

var res = sortListMap(chordtypes);
print(res);
Run Code Online (Sandbox Code Playgroud)

==>

{ omit3: [0, 7], 
  maj: [0, 4, 7], 
  sus2: [0, 2, 7], 
  sus4: [0, 5, 7], 
  #5: [0, 4, 8], 
  M7: [0, 4, 7, 11], 
  m7: [0, 3, 7, 10], 
  6: [0, 4, 7, 9], 
  9: [0, 4, 7, 10, 14], 
  +9: [0, 4, 8, 10, 14], 
  +7b9#11: [0, 4, 8, 10, 13, 18] }
Run Code Online (Sandbox Code Playgroud)

  • 其次:Javascript肯定是一种混乱的语言.有了Dart,我们可以建立一个干净的解决方案,所以我们必须.我更新后只使用LinkedHashMap,@ marcus也应该只使用它,因为它的地图顺序很重要.再次感谢. (2认同)