用另一个索引数组对数组进行排序 [英] Sorting an array by another index array

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

问题描述

我正在遍历数组对,我需要按另一个的顺序对它们进行排序.

I'm iterating over array couples and I need to sort one by the order of the other.

说我有这两个数组:

aLinks = [4,5,6]
bLinks = [1,2,3,4,5,6]

我需要返回:

aLinks = [4,5,6]
bLinks = [4,5,6,1,2,3]

表示我需要先匹配第一个数组,然后再匹配其他数组的项, 尽可能按顺序排序.

meaning that i need to have the items that match first array first and than the rest, sorted by order if possible.

我正在使用d3,因此我正在使用forEach浏览链接集并保存aLinks的顺序.

I'm working with d3 so I'm using forEach to go through the link sets and save the order of aLinks.

我不知道如何将此订单应用于bLinks

I don't know how to apply this order to bLinks

var linkOrder = [];

linkSets.forEach(function(set, i) {
  linkOrder = [];

  set.aLinks.forEach(function(link,i){
    linkOrder.push(link.path);
  })
});

推荐答案

您可以这样做:

  1. 将匹配项从第二个数组中取出到一个临时数组中
  2. 排序临时数组
  3. 排序仅包含不匹配项的第二个数组
  4. 将第二个数组连接到temp数组

代码-用户提供的修复程序:baslikikum

var first = [4,5,6];
var second = [1,7,3,4,6,5,6];
var temp = [], i = 0, p = -1;

// numerical comparator
function compare(a, b) { return a - b; }

// take out matching items from second array into a temp array
for(i=0; i<first.length; i++) {
    while ((p = second.indexOf(first[i])) !== -1) {
        temp.push(first[i]);
        second.splice(p, 1);
    }
}

// sort both arrays
temp.sort(compare);
second.sort(compare);

// concat
temp = temp.concat(second);
console.log(temp);

工作演示: http://jsfiddle.net/kHhFQ/

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

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