1

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.

4 Answers 4

2

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);

1
  • 1
    @ThomasWikman, "from greatest to least". i read descending. casting is implicit with minus operator. Commented Dec 14, 2019 at 21:10
2

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);

2
  • this gives the wrong order. - and no number needed, because of the minus oerator. this converts all operands to a number. Commented Dec 14, 2019 at 21:16
  • Updated the answer to be nothing more than needed. Ty Commented Dec 14, 2019 at 21:21
0

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);
-1

You can use below helper to sort array of strings in javascript:

data.sort((a, b) => a[key].localeCompare(b[key]))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.