19

I have a JSON array and I am trying to sort it by value. The problem I am having is that I am not able to keep the JSON structure with my sorting.

Here is the JSON array:

{
  caffeineoverdose: '2517',
  workhardplayhard: '761277',
  familia: '4633452'
}

I would like something like this:

{
  familia: '4633452',
  workhardplayhard: '761277',
  caffeineoverdose: '2517
}
Alex W
  • 37,233
  • 13
  • 109
  • 109
basic1point0
  • 321
  • 1
  • 2
  • 7
  • 3
    Either you have a string in JSON format, an array, or most likely a regular javascript object? Which one is it ? – adeneo Jan 07 '14 at 16:55
  • 2
    It's not an array. It's an object. – Eimantas Jan 07 '14 at 16:55
  • 1
    you can't sort an object... but you can create a function and put that values into an array .. then sort. – cocco Jan 07 '14 at 16:56
  • 1
    First off, there is no such thing as a "JSON array". JSON is a string representation of data (like XML or CSV). If it's not a string, it's not JSON. Second, this would be a JavaScript object (not an array). Objects can *not* be sorted in JavaScript, only arrays can. You want your data to be in an array, such as: `[{familia: '4633452'}, {...}]`. then you can sort it. – gen_Eric Jan 07 '14 at 16:57
  • 2
    Those are JavaScript object literals, the syntax is invalid for JSON. – Quentin Jan 07 '14 at 16:57

3 Answers3

25

Here is everything you need.

Like i said already in the comments you can't sort an object.. but you can put it into an array and display the results.

var array=[],obj={
 caffeineoverdose:'2517',
 workhardplayhard:'761277',
 familia:'4633452'
};
for(a in obj){
 array.push([a,obj[a]])
}
array.sort(function(a,b){return a[1] - b[1]});
array.reverse();

DEMO

http://jsfiddle.net/GB23m/1/

cocco
  • 16,442
  • 7
  • 62
  • 77
18

You could convert it into an array of objects:

[{ name: 'caffeineoverdose', number: '2517' }, {name: 'workhardplayhard', number: '761277'}, {name: 'familia', number: '4633452'}]

and then sort by number

array.sort(function(a,b){
    return a.number - b.number;
    }
);
MeVimalkumar
  • 3,192
  • 2
  • 15
  • 26
cejast
  • 957
  • 8
  • 18
6

That's not JSON, and it's not an array. It's a regular JavaScript object, and you cannot impose an ordering on the properties of an object.

If you want to maintain the order of your elements, you need an array (again, this isn't JSON, it is JavaScript):

[ [ 'familia', '4633452'] ,
  [ 'workhardplayhard', '761277'],
  [ 'caffeineoverdose', '2517']
]
user229044
  • 232,980
  • 40
  • 330
  • 338
  • 1
    To add, you can WRITE the object sorted, and you can have it displayed on screen sorted, but once it's defined as an object you lose the order. See http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – brandonscript Jan 07 '14 at 16:59