排序基于另一个数组值的数组JS最快捷的方式? [英] Quickest way to sort a JS array based on another array's values?

查看:132
本文介绍了排序基于另一个数组值的数组JS最快捷的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里也有一些类似的帖子四处漂泊,但我不能找到任何解决相当这一具体问题...
我有配对值的两个数组:

There's some similar posts knocking about but I cant find anything that quite addresses this particular issue... I have two arrays of paired values:

var A=[0.5, 0.6, 0.5, 0.7, 0.8, 0.1]
var B=['a','b','c','d','e','f']
//note: a=0.5, b=0.6, c=0.5, d=0.7, etc

什么是数组排序的最友好的处理器方式,使阵列A在数字按升序排列,该数据结构保持不变?我猜内置的Array.sort(功能)将是最快的,但我不相信的语法。

What's the most processor friendly way to sort the arrays so that array A is in numerical ascending order and the data structure is maintained? I guess built in array.sort(function) would be quickest but I'm not confident of the syntax.

推荐答案

的哈克类,但它的作品。

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.

这篇关于排序基于另一个数组值的数组JS最快捷的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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