字符串数组重要性的Javascript排序

字符串数组重要性的Javascript排序,javascript,angularjs,arrays,sorting,typescript,Javascript,Angularjs,Arrays,Sorting,Typescript,我有一个字符串数组,其中包含服务器检索到的数据。我想根据数组元素的重要性对数组进行排序 这是我的密码: // 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 s

我有一个字符串数组,其中包含服务器检索到的数据。我想根据数组元素的重要性对数组进行排序

这是我的密码:

 // 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);
     }
}
//调用服务器后,通过更改顺序保存信息
让formattedData:Array=this.$scope.sortResult(数据\响应,true);
//这是应该对数据进行排序的函数
公共排序=(arrayToSort:Array,firstList:boolean)=>{
如果(!arrayToSort | |!arrayToSort.length){
返回;
}
让结果:数组=[];
设j:any=null;
让listOfImportance:any=null;
如果(第一名单){
重要性列表=[“史密斯”、“埃尔”、“约翰”、“卡尔”、“彼得”];
}否则{
重要性列表=[“约翰”、“彼得”、“卡尔”、“埃尔”、“史密斯”];
}
for(设i=0,orderLength=listOfImportance.length;i
问题是,如果
data\u response
(因此服务器的结果)是
[“Peter”,“John”]
排序的结果(data\u response,true)
[“Peter”,“John”]
,那么它就没有正确排序。事实上,预期的结果是:
[“约翰”、“彼得”]


也许问题在于服务器响应没有包含重要性列表中的所有项?

我认为您的问题在于行

     return result.concat(arrayToSort);
这应该在函数的最后一行for之外,以便仅在对所有可以排序的内容进行排序之后添加剩余的项

但是,我建议您不要重新发明轮子,而是使用该语言中的默认排序函数。首先,使用优先级函数映射元素,如下所示:

return array.sort((a, b) => priority(a) - priority(b));
优先级函数是将元素映射到其优先级(整数)的函数,例如

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

将按数组中指定的顺序排序;第一个元素的优先级为0,结果中的第一个元素的优先级为1,依此类推。

一种可能的解决方案是:不只是存储名称,而是使用
name
priority
存储和对象,然后,对于您获得的所有数据,根据优先级对它们进行排序(这只是一个整数).sortActions([“Peter”,“John”],true)返回预期结果
[“John”,“Peter”]
->什么是priority()函数?我应该使用该代码而不是“return result.concat(arrayToSort)”并将其置于for循环之外吗?我相信,将返回置于循环之外将单独解决您的问题,但我建议使用更好的方法;要使用sort函数,它知道如何对整数进行排序,并且只实现一个优先级函数,即给定一个元素给它分配一个优先级;例如,您可以使用优先级列表中的位置。
priority()
函数从何而来?@charlietfl他在第三个代码块中使用在我询问后添加的@NiklasHigi定义了它。它以前没有定义