Reputation: 85
I have an array that looks like this:
0123456789123456:14
0123456789123456:138
0123456789123456:0
Basically I need to sort them in order from greatest to least, but sort by the numbers after the colon. I know the sort function is kind of weird but im not sure how I would do this without breaking the id before the colon up from the value after.
Upvotes: 1
Views: 135
Reputation: 705
Assuming the structure of the items in the array is known (like described), you could sort it like this.
const yourArray = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
yourArray.sort((a, b) => (b.split(':')[1] - a.split(':')[1]));
console.log(yourArray);
Upvotes: 2
Reputation: 142
You can use below helper to sort array of strings in javascript:
data.sort((a, b) => a[key].localeCompare(b[key]))
Upvotes: -1
Reputation: 378
You can use sort() and reverse(), like this (try it in your browser console):
var arrStr = [
'0123456789123456:14',
'0123456789123456:138',
'0123456789123456:0'
];
arrStr.sort();
console.log(arrStr);
arrStr.reverse();
console.log(arrStr);
Upvotes: 0
Reputation: 386570
Split the string get the second value and sort by the delta.
const second = s => s.split(':')[1];
var array = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
array.sort((a, b) => second(b) - second(a));
console.log(array);
Upvotes: 2