Gyanesh Gouraw
Gyanesh Gouraw

Reputation: 2021

Sorting json array

function demo() {
            var test = [{
                level: 19,
                title: "hello1"
            }, {
                level: 2,
                title: "hello2"
            },
            {
                level: 5,
                title: "hello5"
            }];

I want to sort this array but can't find a way to do so.

Upvotes: 1

Views: 115

Answers (3)

Lajja Thaker
Lajja Thaker

Reputation: 2041

Please check below code ,

<script type="text/javascript">
var test = [
  {  level: 19, title: "hello1" },
  { level: 2, title: "hello2"},
  { level: 5, title: "hello5" }
];

  // Before Sorting
  document.write("<b>Before Sorting </b><br/>");         
  for (var n = 0; n < test.length; n++) {
      document.write(test[n].level + ' ' + test[n].title+ '<br>');
  }

// ascending order
function SortByLevel(x,y) {
  return x.level - y.level; 
}


function SortByTitle(x,y) {
  return ((x.title == y.title) ? 0 : ((x.title> y.title) ? 1 : -1 ));
}

// Call Sort By Name
test.sort(SortByTitle);

document.write("<br/><b>After Sorting </b> <br/>");   
for(var n=0;n<test.length;n++){
  document.write(test[n].level + ' ' + test[n].title+ '<br>');
}

 </script>

Upvotes: 0

Vinoth
Vinoth

Reputation: 647

You can create a sort function like:

function sortBy(prop){
  return function(a,b){
     if( a[prop] > b[prop]){
       return 1;
     }else if( a[prop] < b[prop] ){
       return -1;
     }
     return 0;
  }
 }

//Usage
 var test = [{
            level: 19,
            title: "hello1"
        }, {
            level: 2,
            title: "hello2"
        },
        {
            level: 5,
            title: "hello5"
        }].sort( sortBy("level") );

Upvotes: 2

Florent
Florent

Reputation: 12420

You can create a custom sorting function:

// Sort by level
test.sort(function(a, b) {
  return a.level - b.level;
});

Resulting object:

[
  {"level":2,"title":"hello2"},
  {"level":5,"title":"hello5"},
  {"level":19,"title":"hello1"}
]

Upvotes: 6

Related Questions