JSON按值jQuery或JS排序

问题描述 投票:-1回答:1

在标记此副本之前,请知道我在这里尝试了所有可能的答案。

我得到这样的输出,enter image description here

我试过这些,

var jsonObjSeat = jQuery.parseJSON(seatJson);

//jsonObjSeat.sort(function (a, b) {
//    return a.seats.number.localeCompare(b.seats.number);
//});

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

people = sortByKey(jsonObjSeat, 'seats.number');

我需要1A,1C..2A,2C ..等等

在这里小提琴,https://jsfiddle.net/h9548dLc/8/

jquery arrays json sorting
1个回答
0
投票

使用localeCompare(compareString[, locales[, options]]){numeric: true}选项。

function sortBySeat(array) {
  return array.sort(function(a, b) {
    return a.seats.number.localeCompare(b.seats.number, 'en', {
      numeric: true
    });
  });
}

小提琴here

MDN Web docs here

© www.soinside.com 2019 - 2024. All rights reserved.