Sorting an array based on the first digit of a property
I am trying to sort an array based on the first digit occurring in the header.
My attempt was replacing non-numeric characters with `` (title.replace (/ \ D / g, ''). It returns me the numbers, but I'm not sure how to sort the array from that point.
So test0 is first followed by test1, test2 and test3.
model = [
{
"title": "test3"
},
{
"title": "test1"
},
{
"title": "test2"
},
{
"title": "test0"
}
];
+3
source to share
3 answers
You can use regex in Javascript function sort
like below.
var model = [
{
"title": "test3"
},
{
"title": "test1"
},
{
"title": "test2"
},
{
"title": "test0"
}
];
Update:
As Danilo Valente said in the comments, if your integer starts with 0
, you need to extract the first 0
from the string. Insofar as02 => 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;
});
+5
source to share
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' } ]
+4
source to share