我正在尝试使用数字和字符串对对象数组进行排序。使用数字列排序工作正常,但带字符串的排序似乎有一些问题。我无法在这里找出问题....
result = [{
"title": "test",
"client": "test",
"price": 5000,
"calories": 10,
"eggless": "false",
"date": "2017-09-09"
}, {
"title": "Cinnamon Sugar Fried Apples",
"client": "Frodo Baggins",
"price": 1100,
"calories": 1997.07,
"eggless": true,
"date": "2017-07-06"
}, {
"title": "Cinnamon, Apple, Oatmeal Cake",
"client": "Bruce Banner",
"price": 390,
"calories": 2007.07,
"eggless": false,
"date": "2017-07-09"
}, {
"title": "Cinnamon, Apple, Oatmeal Cake",
"client": "Bruce Banner",
"price": 390,
"calories": 2007.07,
"eggless": false,
"date": "2017-07-09"
}, {
"title": "Chocolate Pancakes With Fruits",
"client": "Bilbo Baggins",
"price": 300,
"calories": 1997.07,
"eggless": true,
"date": "2017-07-04"
}, {
"title": "Chocolate Pancakes With Fruits",
"client": "Bilbo Baggins",
"price": 300,
"calories": 1997.07,
"eggless": true,
"date": "2017-07-04"
}, {
"title": "Cinnamon-Apple Bread",
"client": "Tony Stark",
"price": 250,
"calories": 1500,
"eggless": true,
"date": "2017-07-08"
}, {
"title": "Cinnamon-Apple Bread",
"client": "Tony Stark",
"price": 250,
"calories": 1500,
"eggless": true,
"date": "2017-07-08"
}, {
"title": "Pecan Tart",
"client": "Scrats Squirrel",
"price": 210,
"calories": 1999,
"eggless": true,
"date": "2017-07-08"
}, {
"title": "Pecan Tart",
"client": "Scrats Squirrel",
"price": 210,
"calories": 1999,
"eggless": true,
"date": "2017-07-08"
}, {
"title": "Cinnamon Sugar Fried Apples",
"client": "Frodo Baggins",
"price": 200,
"calories": 1997.07,
"eggless": true,
"date": "2017-07-06"
}];
let column = "title";
let sortOrder = "sort-asc";
if ($.isNumeric(result[0][column])) {
result.sort(function(first, second) {
if (sortOrder === "sort-asc") return first[column] - second[column];
else if (sortOrder === "sort-desc") return second[column] - first[column]; //first[column] < second[column];
});
} else {
if (sortOrder === "sort-asc") result.sort();
else if (sortOrder === "sort-desc") result.sort().reverse();
}
console.log(result);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 0 :(得分:0)
您应该使用String.localeCompare
else {
result.sort(function (first, second) {
if (sortOrder === "sort-asc") return first[column].localeCompare(second[column]);
else if (sortOrder === "sort-desc") return second[column].localeCompare(first[column]); //first[column] < second[column];
});
}
console.log(result);