inspirado en @jwatts1980's answer, y @Alexander's answer here combiné ambas respuestas en una solución rápida y sucia; La matriz principal es la de ser resuelto, el resto se limita a seguir sus índices
NOTA: No es muy eficiente para muy matrices muy grandes
/* @sort argument is the array that has the values to sort
@followers argument is an array of arrays which are all same length of 'sort'
all will be sorted accordingly
example:
sortMutipleArrays(
[0, 6, 7, 8, 3, 4, 9],
[ ["zr", "sx", "sv", "et", "th", "fr", "nn"],
["zero", "six", "seven", "eight", "three", "four", "nine"]
]
);
// Will return
{
sorted: [0, 3, 4, 6, 7, 8, 9],
followed: [
["zr", th, "fr", "sx", "sv", "et", "nn"],
["zero", "three", "four", "six", "seven", "eight", "nine"]
]
}
*/
Es posible que desee cambiar el método de firma/retorno estructura, pero eso debería ser fácil sin embargo.Lo hice de esta manera porque lo necesitaba
var sortMultipleArrays = function (sort, followers) {
var index = this.getSortedIndex(sort)
, followed = [];
followers.unshift(sort);
followers.forEach(function(arr){
var _arr = [];
for(var i = 0; i < arr.length; i++)
_arr[i] = arr[index[i]];
followed.push(_arr);
});
var result = {sorted: followed[0]};
followed.shift();
result.followed = followed;
return result;
};
var getSortedIndex = function (arr) {
var index = [];
for (var i = 0; i < arr.length; i++) {
index.push(i);
}
index = index.sort((function(arr){
/* this will sort ints in descending order, change it based on your needs */
return function (a, b) {return ((arr[a] > arr[b]) ? -1 : ((arr[a] < arr[b]) ? 1 : 0));
};
})(arr));
return index;
};
¿Existe la posibilidad de cambiar la forma en que almacena los datos? Para matrices anidadas, u objetos – zerkms
Voy a adivinar y decir que no hay forma de hacerlo con el código que ha publicado actualmente. Cada matriz no almacena suficiente información dentro de ella. El conjunto de nombres en cualquier punto dado no sabe si se ha cambiado, no hay ninguna propiedad que tenga un orden de clasificación o similar. –
posible duplicado de [JavaScript: manipular dos matrices] (http://stackoverflow.com/questions/8862220/javascript-manipulate-two-arrays) –