在JavaScript中对数组数组进行排序 [英] Sort an array of arrays in JavaScript

查看:51
本文介绍了在JavaScript中对数组数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对内部带有整数的数组的数组进行排序,例如:

I'm trying to sort an array of arrays with integers inside, for example:

var array = [[123, 3], [745, 4], [643, 5], [643, 2]];

如何对它进行排序以返回如下所示的内容?

How can I sort it in order to return something like the following?

array = [[745, 4], [643, 2], [643, 5], [123, 3]];

推荐答案

您可以将自定义比较函数传递给 Array.prototype.sort(),如下所示:

You can pass a custom comparison function to Array.prototype.sort(), like so:

var sortedArray = array.sort(function(a, b) { return a - b; });

这将按升序对整数数组进行排序.比较函数应返回:

This would sort an array of integers in ascending order. The comparison function should return:

  • 如果希望 a 出现在 b
  • 之前,则小于 0 的整数
  • 如果希望 b 出现在 a
  • 之前,则大于 0 的整数如果 a b 相同,则
  • 0
  • an integer that is less than 0 if you want a to appear before b
  • an integer that is greater than 0 if you want b to appear before a
  • 0 if a and b are the same

因此,在此示例中,您需要以下内容:

So, for this example you would want something like:

var sortedArray = array.sort(function(a, b) {
  return b[0] - a[0];
});

如果要对每个子数组的两个元素进行排序(即按第一个元素降序排序,则如果它们相同,然后按第二个元素降序排序),则可以执行以下操作:

If you wanted to sort on both elements of each sub-array (ie. sort by the first element descending, then if they are the same then sort by the second element descending), you could do this:

var sortedArray = array.sort(function(a, b) {
  if (a[0] == b[0]) {
    return a[1] - b[1];
  }
  return b[0] - a[0];
});

请参见 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort 了解更多信息.

这篇关于在JavaScript中对数组数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆