JavaScript 中的多重排序

问题描述 投票:0回答:9

我有一个像这样的对象数组:-

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() 对其进行排序?

javascript arrays sorting
9个回答
6
投票

您可以使用逻辑 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; }


2
投票

使用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;
});

1
投票

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);


0
投票
<!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>

就像这样......


0
投票

使用 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>");
}

这里运行代码https://jsfiddle.net/bhupeshkushwaha/jv3mng0y/


0
投票

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=example

排序方法可以方便地与函数表达式(和闭包)一起使用:

本文讲的是两种使用方式

Array.sort()

其中之一就是您正在寻找的确切解释 - 将

 compareFunction
传递给
sort()

的方法参数

这将允许您指定任何您想要的函数(在合理范围内)来定义排序顺序。

例如:

arrayname.sort(function(a, b){
    return b-a;
});

将返回按降序排列的数组


0
投票

您可以使用自定义排序功能对数组进行排序。请使用链接了解更多有关排序功能的信息。

您可以使用以下代码进行排序。

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);


0
投票

您可以提供一个

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);


0
投票

简单易懂:

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;
   };
}

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