gpt4 book ai didi

javascript - 如何根据一个(字符串和数字)对三个(更多)数组进行排序

转载 作者:行者123 更新时间:2023-11-28 17:37:53 25 4
gpt4 key购买 nike

我想对第一个数组进行排序,并使第二个数组和第三个数组遵循与第一个数组相同的排序。如果我选择对第二个进行排序,其他两个将再次排序。正如您在下面看到的,我需要它来处理字符串和数字。任何有关良好算法的建议将不胜感激。最好使用 Push() 方法。

    let array_one  = ["bravo_one", "charlie_two", "alpha_three", "echo_four", "delta_five"]
let array_two = [1, 2, 3, 4, 5]
let array_three = ["golf_one", "zulu_two", "tango_three", "november_four", "kilo_five"]


// Some Logic expected here
let new_one = array_one.sort(function(a, b){
return (a.localeCompare(b));
})

let new_two = []
let new_three = []

// Exprected Output
console.log(new_one); // ["alpha_three", "bravo_one", "charlie_two", "delta_five", "echo_four"]
console.log(new_two); // [3, 1, 2, 5, 4]
console.log(new_three); // ["tango_three", "golf_one", "zulu_two", "kilo_five", "november_four"]

// Some Logic expected here
let new_one = []

let new_two = array_two.sort(function(a, b){
return b.length - a.length;
})

let new_three = []

// Exprected Output
console.log(new_one); // ["bravo_one", "charlie_two", "alpha_three", "echo_four", "delta_five"]
console.log(new_two); // [1, 2, 3, 4, 5]
console.log(new_three); // ["golf_one", "zulu_two", "tango_three", "november_four", "kilo_five"]


// Some Logic expected here
let new_one = []

let new_two = []

let new_three = array_three.sort(function(a, b){
return (a.localeCompare(b));
})

// Exprected Output
console.log(new_one); // ["bravo_one", "delta_five", "echo_four", "tango_three", "charlie_two"]
console.log(new_two); // [1, 5, 4, 3, 2]
console.log(new_three); // ["golf_one", "kilo_five", "november_four", "tango_three", "zulu_two"]

最佳答案

array_onearray_twoarray_third 看起来它们应该是一个对象。特别是当 array_one[0]array_two[0]array_third[0] 包含相关数据时。

首先更改获取数据的方式,或者:

var bigarray = array_one.map(function(_,i) {
return {
name: array_one[i],
number: array_two[i],
extra: array_three[i]
}
);

现在您可以排序:

bigarray.sort(function(a,b) {
return a.name.localeCompare(b.name);
});

并根据需要进行迭代。

关于javascript - 如何根据一个(字符串和数字)对三个(更多)数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48664066/

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