简体   繁体   中英

Sorting 2D javascript array

I have an array containing a list of tags and count.

tags_array[0] = tags;
tags_array[1] = tags_count;

I need to sort the arrays base on the count so that I can pick out the top few tags.

Supposing tags and tags_count are 2 arrays of same length, I would first build a proper array of objects :

var array = [];
for (var i=0; i<tags_count.length; i++) {
    array.push({tag:tags[i], count:tags_count[i]});
}

And then sort on the count :

array.sort(function(a, b) {return a.count-b.count});

If you need to get your arrays back after that, you may do

for (var i=0; i<array.length; i++) {
    tags[i] = array[i].tag;
    tags_count[i] = array[i].count;
}

Demonstration

Sort one, while storing the sort comparisons. Then sort the other using those results:

var res = [];
tags_count.sort( function( a, b ){ return res.push( a=a-b ), a; } );
tags.sort( function(){ return res.shift(); } );

Assuming that both tags and tags_count are arrays with the same length (that part of the question wasn't too clear), the following is one way to do the trick.

var tags_array = new Array();

for (var i = 0; i < tags.length; i++)
{
    tags_array[i] = {};
    tags_array[i].tagName = tags[i];
    tags_array[i].tagCount = tags_count[i];
}

tags_array.sort(function(a,b){return b.tagCount-a.tagCount});

One should note that it might be possible to structure the data in this way from the start instead of rewriting it like this, in which case that is preferable. Likewise, a better structure can be used to save the data, but this will work.

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