简体   繁体   中英

How to sort a 1D array based on a 2D array?

In JavaScript, I have 2 arrays.

One is a 1D array and other is a 2D array

The content of the 1D array is:

a[0] = "Germany";
a[1] = "England";
a[2] = "America";
a[3] = "France";

2D array content is:

a[0][0] = "America";
a[1][0] = "England";
a[2][0] = "France";
a[3][0] = "Germany";

How can I make the ordering of the 1D array be same as the 2D array?

That is, I want the final result of the 1D array to be:

a[0] = "America";
a[1] = "England";
a[2] = "France";
a[3] = "Germany";

Is it possible for me to do such an action?

How are the two arrays being created? You might be better off with a map... something like:

var a = {'America':'0', 'England':'1', 'France':'2', 'Germany':'3'};

And then you can access them like:

a['America'] to get 0, or assign them with a['England']=4;

If you already have the sorted structure in the other array, why not just copy each element from the 2D array over to the 1D array.

a[i] = a[i][0]
//Where i goes from 0 to 3 in this case

This would save time & computing resources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM