且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

排序基于另一个数组值的数组JS最快捷的方式?

更新时间:2023-08-29 11:13:04

的哈克类,但它的作品。

Kind of hacky, but it works.

var A = [0.5, 0.6, 0.5, 0.7, 0.8, 0.1];
var B = ['a', 'b', 'c', 'd', 'e', 'f'];

var all = [];

for (var i = 0; i < B.length; i++) {
    all.push({ 'A': A[i], 'B': B[i] });
}

all.sort(function(a, b) {
  return a.A - b.A;
});

A = [];
B = [];

for (var i = 0; i < all.length; i++) {
   A.push(all[i].A);
   B.push(all[i].B);
}    

console.log(A, B);

的jsfiddle

0.1, 0.5, 0.5, 0.6, 0.7, 0.8
["f", "a", "c", "b", "d", "e"]

基本上,我们正在与之间的 A B 新阵列中明确领带制作对象,然后排序() ING的。

Basically, we are making objects with a clear tie between A and B within a new array, and then sort()ing that.

然后我回去重建原来的两个数组。

Then I go back and rebuild the original the two arrays.

月Örlygsson使得在评论好点。相反,产生对象像 {A:0.5,B:'A'} ,他建议放置 A B 值数组像 [0.5,'一']

Már Örlygsson makes a good point in the comments. Instead of producing an object like {A: 0.5, B: 'a'}, he suggests placing the A an B values in arrays like [0.5, 'a'].

此的的更快,但如果需要调试所有阵列它会略少可读性。我要离开这个给你,如果你遇到性能问题,型材这两种方法,并选择最快的。

This should be faster, though it will be slightly less readable if needing to debug the all array. I'll leave this up to you, if you are experiencing performance issues, profile both these methods and choose the fastest.