Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a JSON array object using Javascript by value [duplicate]

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
}
like image 521
basic1point0 Avatar asked Jan 07 '14 16:01

basic1point0


2 Answers

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/

like image 100
cocco Avatar answered Oct 18 '22 09:10

cocco


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;
    }
);
like image 30
cejast Avatar answered Oct 18 '22 09:10

cejast