我有一个像这样的对象数组:-
var arr = [ {total : 20, name: David},
{total : 10, name: Joe},
{total : 15, name: Tracy},
{total : 20, name: Joel},
{total : 15, name: Michael},
{total : 10, name: Arnold},
{total : 15, name: Paul},
]
我需要先按total对它们进行排序,然后如果两个的total相同,我需要按name
对它们进行排序排序后我的预期结果应该如下:
var arr = [ {total : 20, name: David},
{total : 20, name: Joel},
{total : 15, name: Michael},
{total : 15, name: Paul},
{total : 15, name: Tracy},
{total : 10, name: Arnold},
{total : 10, name: Joe},
]
谁能告诉我如何使用 Array.sort() 对其进行排序?
您可以使用逻辑 OR 链接排序标准,并使用 delta 表示
total
,使用 String#localeCompare
表示 name
。
// Sort by total then name.
var array = [
{total: 20, name: 'David'},
{total: 10, name: 'Joe'},
{total: 15, name: 'Tracy'},
{total: 20, name: 'Joel'},
{total: 15, name: 'Michael'},
{total: 10, name: 'Arnold'},
{total: 15, name: 'Paul'}
];
array.sort(function (a, b) {
return b.total - a.total || a.name.localeCompare(b.name);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用Array.sort(callback),回调函数有两个参数a、b,分别是arrary中的item,如果<0 a lt b else if = 0 a eq b else > 0 a gt b
则返回一个int值arr.sort(function(a,b){
return a.total == b.total ? (a.name > b.name ? 1: -1) : a.total-b.total;
});
var array = [{ total: 20, name: 'David' }, { total: 10, name: 'Joe' }, { total: 15, name: 'Tracy' }, { total: 20, name: 'Joel' }, { total: 15, name: 'Michael' }, { total: 10, name: 'Arnold' }, { total: 15, name: 'Paul' }];
array.sort(function(a, b) {
return totalCompare(a, b) || a.name.localeCompare(b.name);
});
function totalCompare(a, b) {
if (a.total === b.total) {
return 0;
}
return b.total - a.total;
}
console.log(array);
<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>
就像这样......
使用 sort() 方法
var data = [
{total : '20', name: 'David'},
{total : '10', name: 'Joe'},
{total : '15', name: 'Tracy'},
{total : '20', name: 'Joel'},
{total : '15', name: 'Michael'},
{total : '10', name: 'Arnold'},
{total : '15', name: 'Paul'},
]
data.sort(function (x, y) {
var n = x.total - y.total;
if (n != 0) {
return n;
}
return x.name - y.name;
});
var i;
for (i = 0; i < data.length; i++) {
document.write("<p>total:" + data[i].total +" name:" + data[i].name + "</p>");
}
排序方法可以方便地与函数表达式(和闭包)一起使用:
本文讲的是两种使用方式
Array.sort()
其中之一就是您正在寻找的确切解释 - 将
compareFunction
传递给 sort()
的方法参数
这将允许您指定任何您想要的函数(在合理范围内)来定义排序顺序。
例如:
arrayname.sort(function(a, b){
return b-a;
});
将返回按降序排列的数组
您可以使用自定义排序功能对数组进行排序。请使用链接了解更多有关排序功能的信息。
您可以使用以下代码进行排序。
arr.sort((a,b) => (b.total === a.total ? (a.name > b.name) : b.total - a.total));
这是您问题的解决方案。
var arr = [ {total : 20, name: 'David'},
{total : 10, name: 'Joe'},
{total : 15, name: 'Tracy'},
{total : 20, name: 'Joel'},
{total : 15, name: 'Michael'},
{total : 10, name: 'Arnold'},
{total : 15, name: 'Paul'}];
arr.sort((a,b) => (b.total === a.total ? (a.name > b.name) : b.total - a.total));
console.log(arr);
您可以提供一个
sortObject
,其中包含按键及其各自的方向(按排序顺序):
const sortObject = {
total: -1, // Descending
name: 1, // Ascending
};
然后您可以使用该对象循环遍历数组进行排序:
const arr = [
{ total: 20, name: 'David' },
{ total: 10, name: 'Joe' },
{ total: 15, name: 'Tracy' },
{ total: 20, name: 'Joel' },
{ total: 15, name: 'Michael' },
{ total: 10, name: 'Arnold' },
{ total: 15, name: 'Paul' },
];
// Enter keys by sort order. Key values are -1 for descending and 1 for ascending.
const sortObject = {
total: -1,
name: 1,
};
// Get the keys of sortObject.
const sortKeys = Object.keys(sortObject);
const sortedArray = arr.sort((a, b) => {
let sorted = 0;
let index = 0;
// Loop until sorted or until the sort keys have been processed.
while (sorted === 0 && index < sortKeys.length) {
const key = sortKeys[index];
const sortDirection = sortObject[key];
if (a[key] === b[key]) { // If the values are the same, do not change positions.
sorted = 0;
} else { // Switch positions if necessary. If b[key] > a[key], multiply by -1 to reverse directions.
sorted = a[key] > b[key] ? sortDirection : -1 * sortDirection;
}
index++;
}
return sorted;
});
console.log(sortedArray);
简单易懂:
var homes = [
{ 'city': 'Dallas', 'state': 'TX', 'zip': '75201', 'price': '162500'},
{ 'city': 'Bevery Hills', 'state': 'CA', 'zip': '90210', 'price': '319250'},
{ 'city': 'Dallas', 'state': 'TX', 'zip': '75000', 'price': '556699'},
{ 'city': 'New York', 'state': 'NY', 'zip': '00010', 'price': '962500'}
];
homes.sort(compareMultiple(['zip', '-state', 'price']));
function compareMultiple (criteria) {
return function (a, b) {
for (let key of criteria) {
var order = key.includes('-') ? -1 : 1;
if (!a[key]) return -order;
if (!b[key]) return order;
if (a[key] > b[key]) return order;
if (a[key] < b[key]) return -order;
}
return 0;
};
}