Even though constructing Objects from the multiple arrays may be ideal. You can also do it without the object creation overhead using indirection.
/* An array of indexes */
var idx = [];
for (var i = 0; i < Name.length; i++) {
idx.push(i);
}
/* A shorthand function */
var comparator = function(arr) {
return function(a, b) {
return ((arr[a] < arr[b]) ? -1 : ((arr[a] > arr[b]) ? 1 : 0));
};
};
/* Sort by Age */
idx = idx.sort(comparator(Age));
/* Get the sorted order */
for (var i = 0; i < Name.length; i++) {
console.log(Name[idx[i]], Age[idx[i]], Gender[idx[i]]);
}?
The idx
array contains indexes to the elements of the other arrays, idx[i]
. By using indirection you can access the element in Name
, Age
and Gender
; that is, Name[idx[i]]
.
If performance is a problem then constructing the objects may be faster using in-place sorting, if you just do it once. Otherwise, I would use the indirection without never touching the real arrays.
There you go.
Note: The comparator
function is just an example, you need to actually create your own comparator functions based on your criteria.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…