簡體   English   中英

Javascript對字符串數組的重要性排序

[英]Javascript sort for importance an Array of strings

我有一個字符串數組,其中包含服務器檢索到的數據。 我想根據其元素的重要性對該數組進行排序。

這是我的代碼:

 // once the server is called, save the information by changing the order
let formattedData: Array<string> = this.$scope.sortResult(data_response, true);

// This is the function that should sort the data
public sortActions = (arrayToSort: Array<string>, firstList: boolean) => {
    if (!arrayToSort || !arrayToSort.length) {
        return;
    }

    let result: Array<string> = [];
    let j: any = null;

    let listOfImportance: any = null;
    if(firstList){
        listOfImportance = ["Smith", "El", "John", "Karl", "Peter"];
    } else {
        listOfImportance = ["John", "Peter", "Karl", "El", "Smith"];
    }

     for (let i = 0, orderLength = listOfImportance.length; i < orderLength; i++) {
         let currentOrder = listOfImportance[i];
         while (-1 != (j = $.inArray(currentOrder, arrayToSort))) {
             result.push(arrayToSort.splice(j, 1)[0]);
         }
         return result.concat(arrayToSort);
     }
}

問題是,如果data_response (這樣服務器的結果),例如, ["Peter", "John"]的結果sortActions(data_response, true)["Peter", "John"]那么它沒”不能正確排序。 實際上,預期結果將是: ["John", "Peter"]

也許問題在於服務器響應未包含重要性列表中的所有項目?

我想你的問題是線

     return result.concat(arrayToSort);

這應該在函數的for最后一行之外,以便僅在對所有可以排序的內容進行排序之后才添加其余項。

但是,我建議您不要重新發明輪子,而是使用該語言的默認排序功能。 首先,使用優先級函數映射元素,如下所示:

return array.sort((a, b) => priority(a) - priority(b));

優先級函數是一種將元素映射到其優先級(整數)的函數,例如,

const priority = el => listOfImportance.indexOf(el);

將按數組中指定的順序排序; 第一個元素的優先級為0,結果中的第一個元素的優先級為1,依此類推。

暫無
暫無

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

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