1
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.

3 Answers 3

6

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"}
]
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.