-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?

1
  • 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". Commented Aug 4, 2013 at 17:22

1 Answer 1

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; });
2
  • Is there really a need to answer that for the 1000th time? Just mark as a duplicate. Commented Aug 4, 2013 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...) Commented Aug 4, 2013 at 11:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.