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?
You can sort the array using the sort
function.
Firstly, truncate the number to remove the '
and then convert the value into an Number
using the Number
Object.
Following is a code with sample data, i have taken a shorter version of the Array to demonstrate.
var array = [];
array.push({Registration_Number: "'1"},
{Registration_Number: "'11"},
{Registration_Number: "'12"},
{Registration_Number: "'-5"},
{Registration_Number: "'8"}
);
array.sort((x,y) => {
var xInt = new Number(x.Registration_Number.substring(1,x.length));
var yInt = new Number(y.Registration_Number.substring(1,x.length));
return xInt - yInt;
});
console.log(array);