简体   繁体   English

对2D javascript数组进行排序

[英]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 : 假设tagstags_count是两个长度相同的数组,我首先会构建一个合适的对象数组:

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. 假设标签和tags_count都是长度相同的数组(问题的一部分不太清楚),以下是一种方法。

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. 同样,可以使用更好的结构来保存数据,但这样可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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