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

Sign up to request clarification or add additional context in comments.

1 Comment

@ThomasWikman, "from greatest to least". i read descending. casting is implicit with minus operator.
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 Comments

this gives the wrong order. - and no number needed, because of the minus oerator. this converts all operands to a number.
Updated the answer to be nothing more than needed. Ty
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);

Comments

-1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.