user1931780
user1931780

Reputation: 466

Sorting of array by another (not related) array

I have two arrays of the same length. First array is static with data of such format a = [['q', 10], ['s', 20], ['z', 40], ['d', 15]] and another array b = [1, 0, 0, 1]. So ['q', 10] in mind is related to 1, ['s', 20] - to 0, ['z', 40] to 0, ['d', 15] to 1. Then I do some sorting of the first array and receive, for example, a = [['d', 15], ['s', 20], ['q', 10], ['z', 40]]. So in what way can I change second array to receive b = [1, 0, 1, 0]?

Important. It is not possible to add/change any data in first array.

Upvotes: 1

Views: 114

Answers (3)

wirey00
wirey00

Reputation: 33661

You can keep an array of the return values of the first sort..

var c = [];
var newa = a.sort(function(a,b){
    var ret = a[1] - b[1];// whatever you're sorting on
    c.push(ret); // save return value
    return ret;
});

Then do the same with the second sort.

// go through and sort b the same way
var i=0;
var newb = b.sort(function(){
   return c[i++];
});

Upvotes: 1

Samuel Reid
Samuel Reid

Reputation: 1756

If you want a function to use in sorting that will swap elements in both arrays at the same time,

function swap(array1,array2,a,b) {
  temp = array1[a];
  array1[a] = array1[b];
  array1[b] = temp;
  temp = array2[a];
  array2[a] = array2[b];
  array2[b] = temp;
}

So then you can do

a = [0,1,2,3];
b = [0,1,2,3];
swap(a,b,0,1);

And you'll end up with

a: [1,0,2,3];
b: [1,0,2,3];

Otherwise, if you're actually looking to sort one array in ascending or descending order and have the other array be sorted according to how the first was sorted, check out php.js's array_multisort here: http://phpjs.org/functions/array_multisort/

And for some extra documentation on array_multisort, http://php.net/manual/en/function.array-multisort.php

Upvotes: 0

Pointy
Pointy

Reputation: 413702

If you can change the first array temporarily, you can do this:

  1. Augment the first array with an index value for each element:

    for (var i = 0; i < a.length; ++i) {
      a[i] = { value: a[i], index: i };
    }
    
  2. Sort the array. If your sort function is "compare", then you can do it like this:

    a.sort(function(e1, e2) {
      return compare(e1.value, e2.value);
    });
    
  3. Now you can make a new "b" by arranging it according to the indexes:

    var newB = [];
    for (i = 0; i < a.length; ++i)
      newB[i] = b[a[i].index];
    b = newB;
    
  4. Now restore the values of "a":

    for (i = 0; i < a.length; ++i)
      a[i] = a[i].value;
    

Upvotes: 2

Related Questions