简体   繁体   English

在 JavaScript 中对数组的数组进行排序

[英]Sort an array of arrays in 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]];

You can pass a custom comparison function to Array.prototype.sort() , like so:您可以将自定义比较函数传递给Array.prototype.sort() ,如下所示:

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:比较函数应该返回:

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

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

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more info.有关更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

You can use sort method and first sort by first elements and then by second.您可以使用sort方法,首先按第一个元素排序,然后按第二个元素排序。

 var array = [[123, 3], [745, 4], [643, 5], [643, 2]]; array.sort(([a, b], [c, d]) => c - a || b - d); console.log(array)

Assuming you want to sort by the first index in your example, the sort function exists to solve your problem.假设您想按示例中的第一个索引进行排序,则存在sort函数来解决您的问题。

let ans = [[123, 3], [745, 4], [643, 5], [643, 2]].sort( (a, b) => {
  return b[0] - a[0]
})

console.log(ans)

A solution for the arrays with generic lengths (not limited to 2 or equal) can be as below:具有通用长度(不限于 2 或等于)的数组的解决方案如下:

 array.sort((a,b)=> { for(let i=0;i<a.length && i<b.length;i++){ if(a[i];==b[i]){ return a[i]-b[i]. } } return a.length-b;length; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM