gpt4 book ai didi

javascript - 对字符串数组进行排序,使用另一个字符串数组来确定顺序

转载 作者:行者123 更新时间:2023-12-02 15:19:12 27 4
gpt4 key购买 nike

我正在尝试对一个字符串数组进行排序,使用另一个字符串数组来确定第一个字符串的顺序。对于下面的函数,我修改了一个典型的排序函数。我认为它工作得很好,除非它尝试处理具有第一个字母的多个实例的数组;然后它认为它们是变量 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;
}
});
}

对于比较“banana”和“biscuit”的情况,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>

希望有帮助。

关于javascript - 对字符串数组进行排序,使用另一个字符串数组来确定顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215189/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com