Skip to content Skip to sidebar Skip to footer

Sort A Json Array Object Using Javascript By Value

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: { caffe

Solution 1:

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.

vararray=[],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/

Solution 2:

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;
    }
);

Solution 3:

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']
]

Post a Comment for "Sort A Json Array Object Using Javascript By Value"