2

I'm completely new to JavaScript; please feel free to correct me on my technical terminology.

I have a set of key value pairs that are being appended to a list. The list is displayed as a dropdown menu where the values of the keys are the displayed options and the keys are included in the HTML tag. My boss has asked me to alphabetically sort those displayed values.

So far, I have iterated through the object with a for...in loop and extracted each key's value into an array. I sorted the array and I can now append the values to the list alphabetically.

What's the best way to keep the keys linked to their respective values, so that when I append the values their appropriate keys can be added as well?

Thanks.

SHORT VERSION: How do I match keys back to their values after copying all values into an array and alphabetically sorting it?

4

3 回答 3

2

您可以在没有单独数组的情况下执行此操作。只需使用比较功能(即比较器)。例如:

var arr = [
    {k: "c", v: 3},
    {k: "b", v: 2},
    {k: "d", v: 4},
    {k: "a", v: 1},
    {k: "e", v: 5}
];

//sort by value
arr.sort(function(a, b) {
   return a.v - b.v;
});

这给了你:

[
   {
      "k": "a",
      "v": 1
   },
   {
      "k": "b",
      "v": 2
   },
   {
      "k": "c",
      "v": 3
   },
   {
      "k": "d",
      "v": 4
   },
   {
      "k": "e",
      "v": 5
   }
]

要根据字符串值进行排序,您可以执行以下操作:

arr.sort(function(a, b) {
    return a.v.localeCompare(b.v);
});
于 2013-07-24T16:01:11.610 回答
0

不要单独对值进行排序,而是通过 2D 数组进行排序 - 数组数组。

所以它看起来像

Key1 | Val1
-----------
Key2 | Val2
-----------
Key3 | Val3

然后根据值进行排序,但同时移动两者。

排序后,它可能看起来像

Key3 | Val3
-----------
Key1 | Val1
-----------
Key2 | Val2

然后,当您提到第一个值时,您会这样做array[0][1],并且对于该值的键,您会这样做array[0][0]

于 2013-07-24T16:00:43.970 回答
0

您需要一个自定义排序功能。

var ar = [ {key: 1, value: "One"}, {key: 2, value: "Two"}, {key: 3, value: "Three"} ];

var sortFunction = function(kv1, kv2) {
    return kv1.value.localeCompare(kv2.value);
};

ar.sort(sortFunction);
于 2013-07-24T16:02:31.977 回答