如何在javascript中按值排序地图?

che*_*ong 12 javascript sorting dictionary

var map = new Map();
map.set("orange",10);
map.set("apple",5);
map.set("banana",20);
map.set("cherry",13);
Run Code Online (Sandbox Code Playgroud)

如何按值对此地图进行排序?

Mir*_*ski 22

const myMap = new Map();
myMap.set("a",3);
myMap.set("c",4);
myMap.set("b",1);
myMap.set("d",2);

// sort by value
const mapSort1 = new Map([...myMap.entries()].sort((a, b) => b[1] - a[1]));
console.log(mapSort1);
// Map(4) {"c" => 4, "a" => 3, "d" => 2, "b" => 1}

const mapSort2 = new Map([...myMap.entries()].sort((a, b) => a[1] - b[1]));
console.log(mapSort2);
// Map(4) {"b" => 1, "d" => 2, "a" => 3, "c" => 4}

// sort by key
const mapSort3 = new Map([...myMap.entries()].sort());
console.log(mapSort3);
// Map(4) {"a" => 3, "b" => 1, "c" => 4, "d" => 2}

const mapSort4 = new Map([...myMap.entries()].reverse());
console.log(mapSort4);
// Map(4) {"d" => 2, "b" => 1, "c" => 4, "a" => 3}
Run Code Online (Sandbox Code Playgroud)


Nin*_*olz 12

哟可以采取不同的方法和变化Symbol.iteratorMap.prototype[@@iterator]()自定义排序结果。

var map = new Map();

map.set("orange", 10);
map.set("apple", 5);
map.set("banana", 20);
map.set("cherry", 13);

map[Symbol.iterator] = function* () {
    yield* [...this.entries()].sort((a, b) => a[1] - b[1]);
}

for (let [key, value] of map) {     // get data sorted
    console.log(key + ' ' + value);
}

console.log([...map]);              // sorted order
console.log([...map.entries()]);    // original insertation order
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


小智 10

您可以缩短该函数并在 ES6 中使用它 - 使用箭头函数(lambda)

 let m2= new Map([...m.entries()].sort((a,b) => b[1] - a[1]))
Run Code Online (Sandbox Code Playgroud)


new*_*guy 5

在 ES6 中,您可以这样做:(假设您的 Map 对象是m)。

[...m].map(e =>{ return e[1];}).slice().sort(function(a, b) {
  return a - b; 
});
Run Code Online (Sandbox Code Playgroud)

展开运算符将 Map 对象转换为数组,然后取出每个子数组的第二个元素构建一个新数组,然后对其进行排序。如果您想按降序排序,只需替换a - bb - a.


Ngu*_*ắng 5

您可以使用列表地图而不是仅使用地图。尝试这个:

var yourListMaps = [];
var a = {quantity: 10, otherAttr: 'tmp1'};
var b = {quantity: 20, otherAttr: 'tmp2'};
var c = {quantity: 30, otherAttr: 'tmp3'};
yourListMaps.push(a);
yourListMaps.push(b);
yourListMaps.push(c);
Run Code Online (Sandbox Code Playgroud)

如果您想按数量排序,您可以:

// Sort c > b > a
yourListMaps.sort(function(a,b){
    return b.quantity - a.quantity;
});
Run Code Online (Sandbox Code Playgroud)

或者

// Sort a > b > c
yourListMaps.sort(function(a,b){
    return a.quantity - b.quantity;
});
Run Code Online (Sandbox Code Playgroud)