繁体   English   中英

排序一个字符串数组,使用另一个字符串数组确定顺序

[英]sort an array of strings, using another array of strings to determine the order

我试图排序一个字符串数组,使用另一个字符串数组来确定第一个的顺序。 对于下面的函数,我修改了一个典型的排序函数。 我认为它工作正常,除了它尝试处理带有第一个字母的多个实例的数组时; 那么它会认为它们是该字母在变量orderRequired中的第一个实例(尽管并非总是如此)。 因此,它将它们并排分组,而不是在我想要的位置分组。

var orderRequired = ['b', 'c', 'a', 'd', 'b', 'e'];
//note orderRequired.indexOf('b') !== orderRequired.lastIndexOf('b');
var arr = ['apple', 'banana', 'biscuit', 'cabbage', 'doughnut', 'eclair'];
var myVar = sortThese(orderRequired, arr);
console.log(myVar); 
// gives: ["banana", "biscuit", "cabbage", "apple", "doughnut", "eclair"]
// but I want: ["banana", "cabbage", "apple", "doughnut", "biscuit", "eclair"]

function sortThese(ordReq, arr){
    return arr.sort(function sortFunction(a,b){
        var indexA = ordReq.indexOf(a[0]);
        var indexB = ordReq.indexOf(b[0]);
        if(indexA < indexB) {
            return -1;
        }else if(indexA > indexB) {
            return 1;
        }else{
            return 0;       
        }
    });
}

对于比较“香蕉”和“饼干”的情况,无论是arr中最早的实例还是结果中的最早实例。 在上面的数组中有两个'b'单词的实例,现在我对可以对该数组进行排序的解决方案感到满意。 完美的解决方案虽然可以排序3个或更多实例。 例如,

var orderRequiredPartTwo = ['b', 'c', 'a', 'd', 'b', 'b', 'e']; // this has 3 'b's
var arrPartTwo = ['banoffee', 'apple', 'banana', 'biscuit', 'cabbage', 'doughnut', 'eclair'];
var myVarPartTwo = sortThese(orderRequiredPartTwo, arrPartTwo);

谢谢!

一种方法是遍历数组,在orderRequired数组中找到索引,使用索引来构建排序后的数组,并在orderRequired中将索引清空:

 var orderRequired = ['b', 'c', 'a', 'd', 'b', 'b', 'e']; var arr = ['banoffee', 'apple', 'banana', 'biscuit', 'cabbage', 'doughnut', 'eclair']; var sortThese = function(orderReq, arr) { var result = []; for (var i = 0, t = arr.length; i < t; i++) { var item = arr[i]; var index = orderReq.indexOf(item[0]); result[index] = item; orderReq[index] = null; } return result; }; var sorted = sortThese(orderRequired, arr); document.getElementById("result").innerHTML = JSON.stringify(sorted); 
 <div id="result"></div> 

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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