BarakChamo
BarakChamo

Reputation: 3575

Sorting an array by another index array

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

Say I have these 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]

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

I'm working with d3 so I'm using forEach to go through the link sets and save 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);
  })
});

Upvotes: 1

Views: 148

Answers (3)

techfoobar
techfoobar

Reputation: 66693

You can do it like:

  1. Take out the matching items from second array into a temp array
  2. Sort the temp array
  3. Sort the second array containing only items that did not match
  4. Concatenate the second array into the temp array

Code - With the fix provided by 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/

Upvotes: 4

adeneo
adeneo

Reputation: 318342

iterate the first array, removing the values from the second array and then appending them to the start of the array to get the right 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

Upvotes: 1

moonwave99
moonwave99

Reputation: 22810

You end up with A + sort(A-B) - so you just need to compute the difference between the 2 arrays. Using some underscore convenience methods for example:

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

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

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

Upvotes: 2

Related Questions