1👍
A simple way is the split the sections and make that into a number you can sort on..
eg. 6.2.3 -> 60203 10.5.1 -> 105010 etc.
The sort is then just a simple matter of subtract one from the other..
example…
const myarray = [
{'secction': '6.2.3','title': 'a'},
{'secction': '6.2.2','title': 'b'},
{'secction': '11.3.1','title': 'bn'},
{'secction': '10.5.1','title': 'z'},
{'secction': '10.4.1', title: 'da'}
];
function num(a) {
var b = a.secction.split(".");
return b[0] * 10000 + b[1] * 100 + b[2];
}
myarray.sort((a,b) => {
return num(a) - num(b);
});
myarray.forEach((a) => console.log(a.secction + ' -> ' + a.title));
- [Vuejs]-Page reload on a dynamic route empties Vuex store (NuxtJS)
- [Vuejs]-“blocked by CORS policy” error with https://streamlabs.com/api/v1.0 endpoint
0👍
The aim is to check first the left part of the number, then the middle part, and the right part at the end.
- If a1 > b1, then return sth >= 1
- If a1 < b1, return sth <= -1
- But if a1 = a2, then check a2 and b2 (and apply this same process again, till a3 and b3)
const myarray = [
{'secction': '6.2.3','title': 'a'},
{'secction': '6.2.2','title': 'b'},
{'secction': '11.3.1','title': 'bn'},
{'secction': '10.5.1','title': 'z'},
{'secction': '10.4.1', title: 'da'}
]
function bySecction(a, b) {
const [a1, a2, a3] = a.secction.split('.')
const [b1, b2, b3] = b.secction.split('.')
return (a1 - b1) && (a2 - b2) && (a3 - b3)
}
myarray
.sort(bySecction)
.reverse()
console.log(myarray)
-1👍
You can sort like this
const myarray = [
{'secction': '6.2.3','title': 'a'},
{'secction': '6.2.2','title': 'b'},
{'secction': '11.3.1','title': 'bn'},
{'secction': '10.5.1','title': 'z'},
{'secction': '10.4.1', title: 'da'}
];
const result = myarray.sort((a, b) => {
const n1 = a.secction.split('.').reverse().map((n, index) => n * (10^index)).reduce((i, j) => i + j, 0);
const n2 = b.secction.split('.').reverse().map((n, index) => n * (10^index)).reduce((i, j) => i + j, 0);
return n1 - n2;
});
console.log(result);
Source:stackexchange.com