0

I am wondering how should be the easy way to solve this problem.

I have an array of strings, something like this:

Array [ "15 Some string", "16 Some string", "13 Some string", "11 Some string", "6 Some string", "8 Some string", "12 Some string", "5 Some string", "9 Some string", "10 Some string" ]

And I would like to sort it by integer, which is the first character of this array (and will be every time), using javascript. My desired output would be:

Array [ "16 Some string", "15 Some string", "13 Some string", "12 Some string", "11 Some string", "10 Some string", "9 Some string", "8 Some string", "6 Some string", "5 Some string" ]

Anyone can help?

3 Answers 3

4

How about simply parsing the string values to numbers

var array = ["15 Some string", "16 Some string", "13 Some string", "11 Some string", "6 Some string", "8 Some string", "12 Some string", "5 Some string", "9 Some string", "10 Some string"];

array.sort((a, b) => parseFloat(b) - parseFloat(a));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

2

Use regex to get the numbers and after it compare the numbers.

const array = [ "15 Some string", "16 Some string", "13 Some string", "11 Some string", "6 Some string", "8 Some string", "12 Some string", "5 Some string", "9 Some string", "10 Some string" ];

array.sort((a,b) => b.match(/\d+/g) - a.match(/\d+/g));

console.log(array);

2 Comments

Amazing! Thank you very much. This helped me.
Are you sure, that you answer only no duplicated questions ?
1

You could match the starting integer value and sort by the delta of it.

function getN(s) {
    return s.match(/^\d+/);
}

var array = ["15 Some string", "16 Some string", "13 Some string", "11 Some string", "6 Some string", "8 Some string", "12 Some string", "5 Some string", "9 Some string", "10 Some string"];

array.sort(function (a, b) {
    return getN(b) - getN(a);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.