【问题标题】:Sort Javascript array containing objects by key value [duplicate]按键值对包含对象的Javascript数组进行排序[重复]
【发布时间】:2017-05-25 01:48:21
【问题描述】:

我正在尝试按数据键的字母顺序对下一个数组进行排序:

array = [
{index: 1,
 data: "d"
},
{index: 2,
 data: "c"
},
{index: 3,
 data: "a"
},
{index: 4,
 data: "f"
},
{index: 5,
 data: "e"
},
{index: 6,
 data: "b"
}
];

这样它会变成如下:

array = [
{index: 3,
 data: "a"
},
{index: 6,
 data: "b"
},
{index: 2,
 data: "c"
},
{index: 1,
 data: "d"
},
{index: 5,
 data: "e"
},
{index: 4,
 data: "f"
}
];

已经找到并尝试过这样的事情:

array.sort(function (a, b) { return a[1] - b[1]; });

但没有成功。有没有一种简单的方法可以实现这一目标?请纯js。

【问题讨论】:

    标签: javascript arrays sorting multidimensional-array nested


    【解决方案1】:

    你需要通过键而不是索引来访问

    let array = [{index: 1, data: "d"},{index: 2, data: "c"},{index: 3, data: "a"},{index: 4, data: "f"},{index: 5, data: "e"},{index: 6, data: "b"}];
    
    array.sort( (f, s) => f.data.localeCompare(s.data) );
    
    console.log(array);

    【讨论】:

      【解决方案2】:

      您可以按属性dataString#localeCompare 进行排序

      var array = [{ index: 1, data: "d" }, { index: 2, data: "c" }, { index: 3, data: "a" }, { index: 4, data: "f" }, { index: 5, data: "e" }, { index: 6, data: "b" }];
      
      array.sort(function (a, b) { return a.data.localeCompare(b.data); });
      console.log(array);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 2021-10-30
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多