[英]Sort a dictionary alphabetically by value in JavaScript
這是我的字典:
const dict = {
"key_1" : "z",
"key_2" : "a",
"key_3" : "b",
"key_4" : "y"
};
我想按值按字母順序對其進行排序,所以它看起來像這樣:
const sorted_dict = {
"key_2" : "a",
"key_3" : "b",
"key_4" : "y",
"key_1" : "z"
};
這是我認為應該起作用的:
var items = Object.keys(dict).map(function(key) {
return [key, dict[key]];
});
items.sort((a, b) => a[1] - b[1]);
console.log(items)
但它根本沒有排序:
[
[
"key_1",
"z"
],
[
"key_2",
"a"
],
[
"key_3",
"b"
],
[
"key_4",
"y"
]
]
為什么排序不起作用?
希望這段代碼對你有幫助
const dict = { key_1: "z", key_2: "a", key_3: "b", key_4: "y", }; const sortable = Object.fromEntries( Object.entries(dict).sort(([, a], [, b]) => a.localeCompare(b)) ); console.log(sortable);
JavaScript 中沒有排序字典之類的東西。 不能保證會保留插入順序或字母順序,即使您有時會產生這樣的錯覺,也不應該依賴它。 如果您需要訂購,您必須使用數組、集合或地圖
以下代碼將按字符碼對字典進行排序,即字母順序:
const dict = {
"key_1" : "z",
"key_2" : "a",
"key_3" : "b",
"key_4" : "y"
};
const sorted = Object.entries(dict)
.sort(([, v1], [, v2]) => v1.toUpperCase().charCodeAt(0) - v2.toUpperCase().charCodeAt(0))
.reduce((obj, [k, v]) => ({
...obj,
[k]: v
}), {})
console.log(sorted)
//{key_2: 'a', key_3: 'b', key_4: 'y', key_1: 'z'}
但是,這僅在值為一個字符時才有效。 你對一個也對更大值進行排序的函數是哪個?
您可以在這里使用String.prototype.localCompare() :
const dict = { "key_1": "z", "key_2": "a", "key_3": "b", "key_4": "y" }; var items = Object.keys(dict).map(function(key) { return [key, dict[key]]; }); items.sort((first, second) => first[1].localeCompare(second[1])); console.log(items);
const dict = { "key_1" : "z", "key_2" : "a", "key_3" : "b", "key_4" : "y" }; let sorted = {}; Object.entries(dict) //enteries gives the arrray [key, value] for each entry .sort((a,b) => { //console.log(a,b); //if value is equal, compare with key if(a[1] == b[1]) return a[0]<b[0] ? -1 : 1; //else compare value return a[1]<b[1] ? -1 : 1; }) .forEach((ele) => { //console.log(ele); //reassign to a new object sorted[ele[0]] = ele[1] }); console.log(sorted);
var items = { "key" : [ "key_1=z", "key_2=a", "key_3=b", "key_4=y" ]}; function proto (thisone, order) { proto[order] = thisone; } function proto2(thisone) { proto2[thisone.split("=")[0]] = thisone.split("=")[1]; } function trierMax (value, order2) { if (!proto2[value.split("=")[0]]) { proto(value, order2); } else { proto("null=zzzzz", order2); } for (var y = 0; y < sp.length; y++) { if (sp[y].split("=")[1] < proto[order2].split("=")[1] && !proto2[sp[y].split("=")[0]]) { proto(sp[y], order2); } } } var sp = items.key; for (var i = 0; i < sp.length; i++) { trierMax(sp[i], i); proto2(proto[i]); } for (var p = 0; p < sp.length; p++) { items.key[p] = proto[p]; } console.log(items);
沒有“排序”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.