2

I am trying to sort an array e.g.

arr = ["Joe1,345", "James,1002", "Bill,24"]. 

I need to order them by number descending but there could be a different amount of numbers on the end. I have tried a bubble sort:

function bubbleSort(a) {
    var swapped;
    do {
        swapped = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i] > a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
    return a;
}

But that didn't work - does anyone know how to achieve this? I've looked at other people doing a similar thing but their answers seem to only have a constant letter in front.

Many Thanks

2
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - use a function that splits on comma: function compareNumbers(a, b) { return a.split(",")[1] - b.split(",")[1]; } Commented May 25, 2016 at 9:50
  • 1
    What happens if there are two names with the same number: ['Joe,100', 'Ann,100']? Commented May 25, 2016 at 9:54

1 Answer 1

3

You could use Array#sort() with an appropriate callback for this task

var arr = ["Joe1,345", "James,1002", "Bill,24"];

arr.sort(function (a, b) {
    var aa = a.split(','),
        bb = b.split(',');

    return bb[1] - aa[1];
});

console.log(arr);

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

5 Comments

As you once pointed out to me, you don't actually need those unary + operators, as - coerces. (Not saying you should remove them. :-) )
We have console.log now, no need for doc.write anymore!
@T.J.Crowder, yes, i was saying that.
i know the console, i was requesting a splitter for the small window for resizing.
@NinaScholz: Yeah, for answers like this one I made this request, which canon implemented very quickly; just waiting for SE to add a UI for it.

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.