简体   繁体   English

使用非数字键对javascript数组进行排序

[英]Sort javascript array with non-numeric keys

Here is my array : 这是我的数组:

var a = [];
a["P.M.L."] = 44;
a["P.CO."] = 56;
a["M.É.D."] = 10;

Now i am trying to sort the array so it looks like : 现在,我试图对数组进行排序,使其看起来像:

["M.É.D." : 10, "P.M.L." : 44, "P.CO." : 56]

I have tried many solutions and none of them have been successfull. 我尝试了许多解决方案,但都没有成功。 I was wondering if one of you had any idea how to sort the array. 我想知道你们中的一个人是否知道如何对数组进行排序。

Simple solution will be: 简单的解决方案是:

a.sort(function(x, y) { 
    return x.name - y.name;
})

Taken straight from the MDN website : 直接从MDN网站获取

a.sort(function (a, b) {
    if (a.name > b.name)
      return 1;
    if (a.name < b.name)
      return -1;
    // a must be equal to b
    return 0;
});

But this really isn't an array, so you'll have to restructure that into one. 但这实际上不是数组,因此您必须将其重组为一个数组。

As mentioned in comments, your issue here is not just the sorting but also how your data structure is set up. 如评论中所述,这里的问题不仅是排序,还在于数据结构的设置方式。 I think what you will actually want here is an array of objects, that looks something like this: 我认为您实际上想要的是一个对象数组,看起来像这样:

var a = [{name: "P.M.L", val: 44},
         {name: "P.CO.", val: 56},
         {name: "M.É.D.", val: 10}];

With this new way of organizing your data, you can sort a by the val property with the following code: 通过这种新的组织数据的方式,您可以使用以下代码按val属性对a进行排序:

a.sort(function(x, y) {
    return x.val - y.val;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM