Sort Data In Node.JS

Yosapat Tambunan picture Yosapat Tambunan · Mar 14, 2017 · Viewed 7.9k times · Source

I am using Node.JS and MongoDB. I've created a report with CSV file and this is my code,

function buildListCsvContent() {
   var array = [];
   var counter = 0;
   for (var i = 0; i < vm.student.length; i++) {
      var row = {
         No: counter + 1
         , Registration_Number: "'" + student.registrationNumber.toString()
         , Name: student.firstName + ' ' + student.lastName
      }
      array.push(row);
      counter++
   }
}


var args = {
   data: array
};

downloadCSV(args);

How can i sort this report by registrationNumber?

Answer

surajck picture surajck · Mar 14, 2017

Here's one method:

for (var i = 0; i < vm.student.length; i++) {
    var row = {
        No: counter + 1
        , Registration_Number: "'" + student.registrationNumber.toString()
        , Name: student.firstName + ' ' + student.lastName
        , reg_no: student.registrationNumber   // Added this key to use in sorting
    }
    array.push(row);
    counter++
 }

Use the array.sort method:

function compareFunction (a, b) {
    // Here a and b are the two values in any particular instance of comparison
    // a is put before b if return condition is true, not swapped if condition is false
    // return <condition>

    return a.reg_no > b.reg_no // For ascending
    return a.reg_no < b.reg_no // For descending
}

array.sort(compareFunction)
//array is sorted at this point

I suggest you play around with the return condition to get a good hang of the working.