Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Sorting multiple arrays at once

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...