Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在jQuery中对数组进行排序?_Jquery_Sorting_Data Structures - Fatal编程技术网

如何在jQuery中对数组进行排序?

如何在jQuery中对数组进行排序?,jquery,sorting,data-structures,Jquery,Sorting,Data Structures,我使用数组来存储文本中出现的特定单词。数据的格式为word:number。 我想按出现次数的降序(即按值)对数组进行排序。 有什么好办法吗?还是应该考虑使用不同的数据结构?< /P> // This is how the array is filled. var matches = ["word1", "word2", "word2", "word3", "word4", "word4", "word4"]; var count = {}; $.each(matches, function

我使用数组来存储文本中出现的特定单词。数据的格式为word:number。 我想按出现次数的降序(即按值)对数组进行排序。 有什么好办法吗?还是应该考虑使用不同的数据结构?< /P>
// This is how the array is filled.
var matches = ["word1", "word2", "word2", "word3", "word4", "word4", "word4"];  

var count = {};
$.each(matches, function(key, value) {
    if(!count[value])
        count[value] = 1;
    else
        count[value]++;
});
循环结束后,我将得到并希望通过降序值进行排序:

count = { 'word1':'1', 'word2':'2', 'word3':'1', 'word4':'3' };
我希望它看起来像什么(按值排序):


我建议您使用某种类型的树,因为它已经具有排序地图的属性。

尝试以下方法:

function sortmyway(data_A, data_B)
{
    return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

请参阅。

OP没有数组,而是对象。真的吗?我看起来不像一个对象,我仍然看到一个数组,当我警告“列表[0]”时看到这个,它给了我“9”。@Rakesh:你特别想解释什么?对象支持
obj[i]
语法。数组是对象的一种特定形式。数组像
[1,2,3]
一样创建,并以数字索引。更一般的对象是用
{1:1,2:2,3:3}
创建的,并且按照您的喜好进行索引。@Rakesh:(事实上,公平地说,OP实际上是指数组。)@Rakesh:您的代码有一个数组。我说OP没有,但它不是一个有效的对象。OP的意思可能是
[“word1”、“word2”、…]
,也可能是他丢了钥匙。对不起,评论仅指第一行(已更改)@这就是我的意思。请编辑你的帖子以更准确地反映你的情况。
function sortmyway(data_A, data_B)
{
    return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]