简体   繁体   中英

Javascript sort for importance an Array of strings

I have an Array of string containing the data retrieved by the Server. I want to sort that Array based on the importance of its elements.

Here is my code:

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

The problem is that if data_response (so the server's result) is, for example, ["Peter", "John"] the result of sortActions(data_response, true) is ["Peter", "John"] , then it didn't sort correctly. In fact, the expected result would be: ["John", "Peter"]

Perhaps the problem is that the server response doesn't contain all the items in the list of importance?

I think your problem is the line

     return result.concat(arrayToSort);

This should outside the for, last line of the function, in order to add the remaining items only after everything that could be sorted was sorted.

However, I'd suggest you don't reinvent the wheel, and use a default sorting function from the language. First, map the elements using a priority function, like so:

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

The priority function is a function that maps an element to it's priority (an integer), for instance,

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

Will sort by the order specified in the array; the first element will be priority 0, and the first in the result, the second will be priority 1, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM