基于来自另一个数组

时间:2016-03-14 01:14:23

标签: javascript

我有阵列arrInt [0,0,2,2,0,2,2,1,1,2,2,2,2,0]。现在我需要创建数组边缘,使得基于arrInt的值,如果包含0的元素与其他元素0匹配,则边缘的源将是索引,而目标将是其他元素的索引。边缘的结果如下所示。我怎么能在javascript中做到这一点?

       var edges = [];

       edges.push({
            source: ,
            target: 
        });

      edges = [{source: 0, destination: 1},{source: 0, destination: 4},{source: 0, destination: 13}, {source: 1, destination: 4},{source: 0,   destination: 13}, {source: 4, destination: 13},{source: 8, destination: 9} {source: 2, destination: 3}, {source: 2, destination: 5},{source: 2, destination: 6},{source: 2, destination: 9}, {source: 2, destination: 10}, {source: 2, destination: 11}, {source: 2, destination: 12},
   {source: 3, destination: 5},{source: 3, destination: 6},{source: 3, destination: 9},{source: 3, destination: 12},{source: 5, destination: 6},{source: 5, destination: 9},{source: 5, destination: 10},{source: 5, destination: 11},{source: 5, destination: 12},{source: 6, destination: 9},{source: 6, destination: 10},{source: 6, destination: 11},{source: 6, destination: 12},{source: 9, destination: 10},{source: 9, destination: 11},{source: 9, destination: 12},{source: 10, destination: 11},{source: 10, destination: 12},{source: 11, destination: 12}]

1 个答案:

答案 0 :(得分:1)

var edges = [];
for(var i = 0; i < arrInt.length; i++)
    for(var j = i + 1; j < arrInt.length; j++)
        if(arrInt[i] === arrInt[j])
            edges.push({ source: i, target: j });

edges将包含所有可能的ij对,其中arrInt[i]等于arrInt[j]。边缘按(source, target)排序。

然后可以按相应的arrInt值对数组进行排序。

edges.sort(function (p1, p2) { return arrInt[p1.source] - arrInt[p2.source]; });