Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 3 arrays :

  • array 1 is "Name" John, Jim, Jack, Jill

  • array 2 is "Age" 25, 30, 31, 22

  • array 3 is "Gender" Male, Male, Male, Female

I have these all listed in a table with a sortable header. Now the sort works fine, it sorts by the "Name" column for example. How can i also make it sort the "Age" and "Gender" arrays to keep them correct. I need to sort all 3 simultaneously.

_nameArray.sort(function(a, b){
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
})

Hope it is explained well enough.

No the structure can not be changed, the way things are it has to be 3 arrays, not one and just sort by the field in the array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...