Sorting an array using another array of indices

I am iterating over arrays of arrays and I need to sort them in the order of the other.

Let's say I have two arrays:

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

      

I need to return:

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

      

means I need to have the elements that match the first array at the beginning, and not the rest, sorted by order, if possible.

I am working with d3, so I use forEach to traverse linksets and keep the order of aLinks.

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


source to share


3 answers


You can do it like:

  • Take out the matched elements from the second array into a temp array
  • Sorting temp array
  • Sorting a second array containing only those elements that don't match
  • Concatenating second array into temp array

Code - with the help of a fix provided by the user: basilikum



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);

      

Working demo : http://jsfiddle.net/kHhFQ/

+4


source


A + sort(A-B)

What you end up with is - so you just need to calculate the difference between the two arrays. Using some underscore methods like:



var A = [4,5,6];
var B = [1,2,3,4,5,6];

var diff = _.difference(A,B);

var result = _.flattern(A, diff.sort());

      

+2


source


repeat the first array, removing the values ​​from the second array, and then adding them to the beginning of the array to get the correct order:

var arr1 = [4,5,6];
var arr2 = [1,2,3,4,6,5];

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

for (i=arr1.length; i--;) {
    arr2.splice(arr2.indexOf(arr1[i]), 1);
    arr2.unshift( arr1[i] );
}

      

FIDDLE

+1


source







All Articles