Muchtar
Muchtar

Reputation: 122

sort arrays in multidimensional array associative to the others

I've three associative arrays with the same length. These arrays are in a multidimensional array. Something like this:

var multi_array = [];
var array_a     = [2,3,4,1,5];
var array_b     = [0,7,9,8,6];
var array_c     = ['A','D','B','A','E'];

multi_array     = [array_a, array_b, array_c];

enter image description here

So if I try to sort multi_array like this:

multi_array[0].sort(function(a,b){
                        if(isNaN(a) || isNaN(b)){
                            return a > b ? 1 : -1;
                        }
                        return a - b;
                    });

It only sorts the first array.

enter image description here

I want, that the other arrays get sorted by the same indecies depends of the sorted one like this:

enter image description here

Upvotes: 1

Views: 69

Answers (2)

Dan Kreiger
Dan Kreiger

Reputation: 5516

Not the cleanest code, but it prints your answer:

var array_a = [2, 3, 4, 1, 5];
var array_b = [0, 7, 9, 8, 6];
var array_c = ['A', 'D', 'B', 'A', 'E'];

// get indices from array_a sorted
var len = array_a.length;
var indices = new Array(len);
for (var i = 0; i < array_a.length; ++i) indices[i] = i;
indices.sort(function(a, b) {
  return array_a[a] < array_a[b] ? -1 : array_a[a] > array_a[b] ? 1 : 0;
});

// sorted array_b and sorted_array_c
var sorted_array_a = [];
var sorted_array_b = [];
var sorted_array_c = [];
for (var i = 0; i < indices.length; ++i) {
  sorted_array_a.push(array_a[indices[i]]);
  sorted_array_b.push(array_b[indices[i]]);
  sorted_array_c.push(array_c[indices[i]])
}

var multi_array = [sorted_array_a, sorted_array_b, sorted_array_c]


console.log(multi_array);

Upvotes: 1

Manoa Razanajatovo
Manoa Razanajatovo

Reputation: 37

You need to sort each array in the multi_array

var multi_array = [];
var array_a     = [2,3,4,1,5]; //1,2,3,4,5 0:1,1:2,2:3,3:0,4:4 
var array_b     = [0,7,9,8,6]; //8,0,7,9,6
var array_c     = ['A','D','B','A','E'];

multi_array     = [array_a, array_b, array_c];

// clone the first array_a
var multi_temp = multi_array[0].slice(0);

// sort the clone
multi_temp.sort(function(a,b){
                    	if(isNaN(a) || isNaN(b)){
                        		return a > b ? 1 : -1;
                    	}
                    	return a - b;
                    });

// get the algorithm of key for sorting
var id = [];
multi_array[0].forEach((val, i) => {
	id[i] = multi_temp.indexOf(val);
} );

// and apply the algorithm in the multi_array
multi_array = multi_array.map(item => {
	var temp = [];
	id.forEach((val, i) => {
		temp[val] = item[i];
	});
	return temp;
});

console.log(multi_array);

Upvotes: 1

Related Questions