-1

I have the following jason Array of objects this array is updated dynamically using signalr So I have to arrange the array once it is updated:

var Con= [
    {
        "Name": "Killy",
        "Team": "1"

    }, {
        "Name": "jack",
        "Team": "2"
    },{
        "Name": "Noor",
        "Team": "1"

    },{
        "Name": "Ramez",
        "Team": "1"

    },{
        "Name": "wala",
        "Team": "2"

    }, {
        "Name": "Sozan",
        "Team": "3"
    }];

how can I sort Names by Team using JavaScript only?

wala rawashdeh
  • 423
  • 5
  • 17
  • You could try one of those new-fangled "search engines" which can scan the Intertubes. Picking the search terms could be a real challenge, but you could try "javascript array sort". –  Aug 04 '13 at 17:22

1 Answers1

5

JavaScript's Array#sort accepts a function that it will call repeatedly with pairs of entries from the array. The function should return 0 if the elements are equivalent, <0 if the first element is "less than" the second, or >0 if the first element is "greater than" the second. So:

Con.sort(function(a, b) {
    if (a.Team === b.Team) {
        return 0;
    }
    return a.Team < b.Team ? -1 : 1;
});

You can do that on one line if you're into that sort of thing (I find it easier to debug if I don't):

Con.sort(function(a, b) { return a.Team === b.Team ? 0 : a.Team < b.Team ? -1 : 1; });
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is there really a need to answer that for the 1000th time? Just mark as a duplicate. – georg Aug 04 '13 at 11:05
  • 1
    @thg435: I have to admit having answered as a knee-jerk reaction. Then I saw the question Juhana pointed out, and voted to close as a dupe. (I'm curious: Why haven't you? Right now there are only two votes, mine and Juhana's...) – T.J. Crowder Aug 04 '13 at 11:05