根据属性的第一个数字对数组进行排序
Sorting an array based on first digit of property
我正在尝试根据标题中遇到的第一个数字对数组进行排序。
我的尝试是用"(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);
});
相关文章:
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- Javascript中的多维数组排序索引问题
- 如何按日期对Javascript对象数组排序
- 数组排序后显示更改
- 当许多元素相等时,Javascript数组排序无法正常工作
- Javascript数组排序速度受字符串长度的影响
- 按唯一键将对象数组排序为数组
- 以 js 为单位的数组排序
- js 数组排序无法正常工作
- 数组排序.论点从何而来
- 不需要的数组排序
- 数组排序不正确/不可预测,使用 indexOf 时
- Javascript将数组排序到树中
- 随后的多维数组排序会产生意外的结果
- 数组排序基于纯javascript搜索文本匹配
- Javascript自定义数组按数组排序
- 使用字符串按属性错误对对象进行数组排序
- 多维数组排序
- JavaScript与PHP在数组排序中的对比
- Javascript-关联数组排序