javascript - 如何根据另一个数组的内容对数组进行排序

标签 javascript angularjs algorithm

我有一个数组 X = [12,14,12,45,12] 和另一个数组 Y = [34,12,23,47,20]。我正在对 X 数组进行排序,所以现在 X = [12,12,12,14,45]。现在我想将 Y 排序为 Y = [34,23,20,12,47]。任何帮助,将不胜感激。谢谢

最佳答案

您可以构建索引数组并使用引用 X 的自定义比较器函数对其进行排序,然后使用该数组对 Y 进行“排序”:

var X = [12,14,12,45,12];
var Y = [34,12,23,47,20];
var xIndexes = [];
X.forEach((value, index) => xIndexes.push(index));

xIndexes.sort((a, b) => X[a] < X[b] ? -1 : X[a] > X[b] ? 1 : 0);

var newX = [];
var newY = [];

xIndexes.forEach((index) => {
  newX.push(X[index]);
  newY.push(Y[index]);
});

console.log(newX);
console.log(newY);

关于javascript - 如何根据另一个数组的内容对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941843/

相关文章:

javascript - 在播放结束时隐藏视频控件

javascript - $ionicScrollDelegate.scrollTop 卡住页面滚动

algorithm - 按顺序查找 k 个最大的元素

javascript - 在 head 中添加 noscript 以包装重定向的有效方法

javascript - 为什么我的 Sieve 在 JavaScript 中这么慢?

javascript - 天气API请求cors错误

javascript - ng-show 未正确更新

html - 通过 Controller 的 ng-show 不工作

swift - 为什么 O(n) 比 O(n^2) 花费的时间更长?

algorithm - 在 MATLAB 中理解和实现细化算法