假设我有一个数组:[0,3,4,2,5,1]
。
我想要做的是对数组进行排序,例如:
["one", "two", "three", "four", "five", "six"]
这样顺序对应第一个数组。
这将是输出:
["one", "four", "five", "three", "six", "two"]
有没有一种简单的方法可以实现这一目标?
答案 0 :(得分:19)
您可以这样做:
function getSorted(arr, sortArr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
console.log(sortArr[i], arr[i]);
result[i] = arr[sortArr[i]];
}
return result;
}
var arr = ["one", "two", "three", "four", "five", "six"];
var sortArr = [0, 3, 4, 2, 5, 1];
alert(getSorted(arr, sortArr));
注意:这假设您传入的数组大小相同,如果情况不是这样,您需要添加一些额外的检查。
答案 1 :(得分:1)
orderedArray= function(arr,order){
return order.map(function(itm){return arr[itm]});
}
var sequence= [0, 3, 4, 2, 5, 1],arr=["one","two","three","four","five","six"]
arr=new orderedArray(arr,sequence);
/* returned value: (Array)
one,four,five,three,six,two
*/
//您可以使订单成为数组的无索引属性, //并调用array.ordered()
Array.prototype.ordered= function(order){
var arr= this;
order=order || this.order;
return order.map(function(itm){
return arr[itm];
});
}
var arr= ["one","two","three","four","five","six"],
sequence= [0, 3, 4, 2, 5, 1];
arr.order=sequence;
arr.ordered()
/* returned value: (Array)
one,four,five,three,six,two
*/
答案 2 :(得分:1)
我在接受电话采访时被问到这个问题。然后在不创建另一个数组的情况下进行,假设数组非常大。我不知道这是否是答案,因为我无法接听电话(该死的!),但这就是我想出来的。
var my_obj_array = ['a', 'b', 'c', 'd'];
var my_indicies = [3, 1, 0, 2];
// desired result ['d', 'b', 'a', 'c']
var temp = {};
for (var i = 0; i < my_indicies.length; i++) {
temp[i] = my_obj_array[i]; // preserve
var j = my_indicies[i];
if (j in temp) {
my_obj_array[i] = temp[j];
delete temp[j];
} else {
my_obj_array[i] = my_obj_array[j];
}
}
答案 3 :(得分:0)
不是你如何得到你的第一个数组,但你可以使用一组对象而不是[0,3,4,2,5,1]
:
var arr = [
{n:0, s:'one'},
{n:3, s:'four'},
{n:4, s:'five'},
{n:2, s:'three'},
{n:5, s:'six'},
{n:1, s:'two'}
]
避免处理它。
答案 4 :(得分:0)
You can use first array as directory for sorting second one using map method:
const firstArray = [0, 3, 4, 2, 5, 1];
const secondArray = ['one', 'two', 'three', 'four', 'five', 'six'];
const result = firstArray.map((item) => {
return secondArray[item];
});
// result = ["one", "four", "five", "three", "six", "two"]
答案 5 :(得分:0)
let inds = [0,3,4,2,5,1];
let x = ["one", "two", "three", "four", "five", "six"];
let x2 = []; //Output
inds.forEach(ind => x2.push(x[ind]));
x2
//(6) ["one", "four", "five", "three", "six", "two"]
答案 6 :(得分:-1)
class test1
{
public static String[] sort(int[] array,String[] str)
{
String[] out=new String[str.length];
for(int i=0;i<str.length;i++)
{
out[i]=str[array[i]];
}
return out;
}
}