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

Sorting an array based on first digit of property

本文关键字:数组 排序 数字 属性 第一个      更新时间:2023-09-26

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

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

因此,test0 首先是 test1、test2 和 test3。

model = [
  {
    "title": "test3"
  },
  {
    "title": "test1"
  },
  {
    "title": "test2"
  },
  {
    "title": "test0"
  }
];

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

var model = [
    {
        "title": "test3"
    },
    {
        "title": "test1"
    },
    {
        "title": "test2"
    },
    {
        "title": "test0"
    }
];

更新:

正如达尼洛·瓦伦特(Danilo Valente)在评论中所说,如果您的整数以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;
});

var model = [{
  "title": "test3"
}, {
  "title": "test1"
}, {
  "title": "test2"
}, {
  "title": "test02"
}, {
  "title": "test0"
}];
// pass a custom sort fn to `.sort()`
var sortedModel = model.sort(function(a, b) {
  // just get the first digit
  return a.title.match(/'d/) - b.title.match(/'d/);
});
console.log(sortedModel);
// [ { title: 'test02' },
//   { title: 'test0' },
//   { title: 'test1' },
//   { title: 'test2' },
//   { title: 'test3' } ]

由于您只想根据第一个数字进行排序,因此您可以使用自定义函数调用.sort,然后使用简单的正则表达式查找第一个数字:

model.sort(function (a, b) {
    var da = a.title.match(/'d/);
    var db = b.title.match(/'d/);
    return parseInt(da) - parseInt(db);
});