根据属性的第一个数字对数组进行排序

Mit*_*all 3 javascript arrays sorting

我正在尝试根据标题中遇到的第一个数字对数组进行排序.

我的尝试是用''替换非数字字符(title.replace(/\D/g,'').它给了我数字,但我不确定如何从这一点对数组进行排序.

因此,test0首先是test1,test2和test3.

model = [
  {
    "title": "test3"
  },
  {
    "title": "test1"
  },
  {
    "title": "test2"
  },
  {
    "title": "test0"
  }
];
Run Code Online (Sandbox Code Playgroud)

Won*_*ket 5

您可以在Javascript的sort函数中使用正则表达式,如下所示.

var model = [
    {
        "title": "test3"
    },
    {
        "title": "test1"
    },
    {
        "title": "test2"
    },
    {
        "title": "test0"
    }
];
Run Code Online (Sandbox Code Playgroud)

更新:

正如Danilo Valente在评论中所述,如果您的整数以a开头,则0需要0从字符串中提取第一个.以来02 => 0

model.sort(function (a, b) {
    //Strips out alpha characters
    a = a.title.replace(/\D/g, '');
    b = b.title.replace(/\D/g, '');

    //sets value of a/b to the first zero, if value beings with zero.
    //otherwise, use the whole integer.
    a = a[0] == '0' ? +a[0] : +a;
    b = b[0] == '0' ? +b[0] : +b;

    return a - b;
});
Run Code Online (Sandbox Code Playgroud)

  • 他希望根据第一个数字排序,但在你的情况下,如果我们有"title02",那么它将出现在"test1"之后. (2认同)