Something I recently realized when trying to sort JSON Arrays on Javascript.

I tried to sort a JSON array I built (using PHP's json_encode function) that looked like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[{
	"1": {
		"id": "1",
		"name": "Kurt Cobain",
		"description": "Singer",
		"birthday": "1967-02-20"
	},
	"2": {
		"id": "2",
		"name": "Dave Grohl",
		"description": "Drummer",
		"birthday": "1969-01-14"
	},
	"3": {
		"id": "3",
		"name": "Krist Novoselic",
		"description": "Bass player",
		"birthday": "1965-05-16"
	}
}]

I couldn't for the life of me understand why won't the JSON object
sort when I tried to use

1
2
JSON.parse(members);
members = members.sort(function(b,a) { return a.name > b.name });

Until I suddenly saw it. The array I was building
using PHP had keys for each object, as oppose to what I
should've done (i.e. NOT giving a key to each object..)
short fix made the JSON string look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[{
    "id": "1",
    "name": "Kurt Cobain",
    "description": "Singer",
    "birthday": "1967-02-20"
}, {
    "id": "2",
    "name": "Dave Grohl",
    "description": "Drummer",
    "birthday": "1969-01-14"
}, {
    "id": "3",
    "name": "Krist Novoselic",
    "description": "Bass player",
    "birthday": "1965-05-16"
}]