排序 Node.JS 中的数据

Sort Data In Node.JS

我正在使用 Node.JS 和 MongoDB。我用 CSV 文件创建了一个报告,并且 这是我的代码,

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

如何按注册号对报告进行排序?

这是一种方法:

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++
 }

使用array.sort方法:

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

我建议您尝试一下 return 条件,以便很好地掌握工作原理。

您可以使用 sort 函数对数组进行排序。

首先,截断数字以删除 ',然后使用 Number 对象将值转换为 Number

以下是带有示例数据的代码,我使用了一个较短版本的数组来演示。

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

-- 对不起,我不能给帖子写评论¯_(ツ)_/¯ --

澄清 surajck 写的内容。根据 mdn 文档,如果你想对数字进行排序,你应该从另一个中减去一个,即

function compareFunction (a, b)
     // you could wrap values in `Number()` to convert them to numbers, but 
     // in case of subtraction it's handled automatically
     return a.reg_no - b.reg_no // For ascending
     return b.reg_no - a.reg_no // For descending
}

array.sort(compareFunction)

如果您返回布尔值,您可能会以不一致的排序结束。

一般回调应该返回一个数字:

If compareFunction(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

If compareFunction(a, b) is greater than 0, sort b to an index lower than a, i.e. b comes first.

如果您在项目中使用 mongoo 数据库 可以使用 .sort({create_at:-1}) 例如:

        Model.find().sort({create_at:-1}).exec(function(err, user) {})