簡體   English   中英

在 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

我建議你玩轉返回條件,以很好地掌握工作。

您可以使用sort函數對數組進行sort

首先,截斷數字以刪除' ,然后使用Number對象將值轉換為Number

以下是帶有示例數據的代碼,我使用了一個較短版本的 Array 來演示。

 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)

如果您返回布爾值,您可能會以不一致的排序結束。

通常應該從回調中返回一個數字:

如果 compareFunction(a, b) 小於 0,則將 a 排序到低於 b 的索引,即 a 在前。

如果 compareFunction(a, b) 返回 0,則使 a 和 b 彼此保持不變,但相對於所有不同元素進行排序。 注意:ECMAscript 標准不保證這種行為,因此並非所有瀏覽器(例如至少可以追溯到 2003 年的 Mozilla 版本)都尊重這一點。

如果 compareFunction(a, b) 大於 0,則將 b 排序到低於 a 的索引,即 b 在前。

如果您在項目中使用 mongoo db 可以使用.sort({create_at:-1})例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM