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?
nameandpriority, then, for all the data u get, order them based on the priority (which will be just an integer).sortActions(["Peter", "John"], true)returns the expected result["John", "Peter"]-> jsfiddle.net/pyx4uyv3