使用Javascript对数字数组进行排序 [英] Using Javascript to sort an array of numeric arrays

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

问题描述

在Javascript中,如果我有一个数组数组,如下所示:

X = [ [1,2,3,4],
      [1,1,2,3],
      [1,1,3],
      [1,4],
      [2,1,2],
      [2,2]
    ]

Javascript对我的数组进行排序,首先比较第一个条目,然后比较第二个,依此类推,以便X.sort()返回以下内容:

[ [1,1,2,3],
  [1,1,3],
  [1,2,3,4],
  [1,4],
  [2,1,2],
  [2,2]
]

我想要的是什么.问题在于,用于比较数组中元素的比较运算符是按字典顺序排列的,因此[10,2] < [2,2],例如

[[10,2],[1,1,3],[2,2]].sort() -> [[1,1,3],[10,2],[2,2]]

我需要它对数字进行排序,以便获得[[1,1,3],[2,2],[10,2]]的排序数组.

我尝试使用function(a,b){return (a-b) }的比较函数,该函数可用于对数字数组进行排序,但这无法正确地对我的数组进行排序,这很有意义(我认为),因为[10,2] - [1,1,3]会产生NaN

如何对数字数组进行排序?

解决方案

正如我在评论中所说,sort函数需要考虑以下事实:它接受数组作为参数而不是普通值.因此,您需要相应地处理它们.

我建议这个

var compFunc = function (a, b) {
    var len = a.length > b.length ? b.length : a.length;

    for(var i=0; i<len; ++i) {
        if(a[i] - b[i] !== 0)
            return a[i] - b[i];
    }

    return (a.length - b.length);
};

它首先尝试查找两个数组的公共长度之间的差异.如果公用长度完全相同,则它将基于数组长度进行排序. 这是工作中的小提琴.

In Javascript, if I have an array of arrays, like the following:

X = [ [1,2,3,4],
      [1,1,2,3],
      [1,1,3],
      [1,4],
      [2,1,2],
      [2,2]
    ]

Javascript sorts my array, comparing first entry first, then second, and so on, so that X.sort() returns the following:

[ [1,1,2,3],
  [1,1,3],
  [1,2,3,4],
  [1,4],
  [2,1,2],
  [2,2]
]

Which is what I want. The problem is that the comparison operator for comparing the elements in the arrays is lexicographical, so [10,2] < [2,2], and, for example,

[[10,2],[1,1,3],[2,2]].sort() -> [[1,1,3],[10,2],[2,2]]

I need it to sort numerically, so that I get a sorted array of [[1,1,3],[2,2],[10,2]].

I tried using a comparison function of function(a,b){return (a-b) }, which would work for sorting an array of numbers, but this fails to properly sort my array, which makes sense (I think) because [10,2] - [1,1,3] yields NaN

How do I go about sorting an array of numeric arrays?

解决方案

As I said in my comment, the sort function needs to account for the fact that it's receiving arrays as arguments and not plain values. So you need to handle them accordingly.

I suggest this;

var compFunc = function (a, b) {
    var len = a.length > b.length ? b.length : a.length;

    for(var i=0; i<len; ++i) {
        if(a[i] - b[i] !== 0)
            return a[i] - b[i];
    }

    return (a.length - b.length);
};

It first tries to look for differences in the common length of the two arrays. If the common length is exactly the same, then it sorts on the basis of array length. Here's a working fiddle.

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

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