根据另一个整数数组对一个数组进行排序 [英] Sort an array based on another array of integers

查看:102
本文介绍了根据另一个整数数组对一个数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组:[0,3,4,2,5,1].

我要对数组进行排序,例如:

What I want to do is sort an array such as:

["one", "two", "three", "four", "five", "six"]

因此顺序对应于第一个数组.

So that the order corresponds to the first array.

这将是输出:

["one", "four", "five", "three", "six", "two"]

有没有简单的方法可以做到这一点?

Is there an easy way to accomplish this?

推荐答案

您可以执行以下操作:

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));

注意:假设您传入的数组大小相等,如果不是这种情况,则需要添加一些其他检查.

Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.

这篇关于根据另一个整数数组对一个数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆