其元素的赋存数组排序 [英] Sort Array by occurrence of its elements

查看:135
本文介绍了其元素的赋存数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找它的元素发生排序数组的优雅的方式。

例如,在

  ['鸭梨','苹果','橙','苹果','橙','苹果']

输出应为

  ['苹果','橙','鸭梨']

我已经通过数组试图循环并保存在另一个临时数组的发生,但这种方法是相当糟糕的。


解决方案

这需要两个循环。

\r
\r

VAR ARR = ['鸭梨','苹果','橙','苹果','橙','苹果'];\r
    //找到使用计数减少\r
    VAR碳纳米管= arr.reduce(函数(OBJ,VAL){\r
        OBJ [VAL] =(OBJ [VAL] || 0)+ 1;\r
        返回OBJ;\r
    },{});\r
    //使用对象的密钥,以获得阵列的所有值\r
    //并通过他们的计数这些键进行排序\r
    VAR分类= Object.keys碳纳米管(CNTs)的.sort(功能(A,B){\r
        返回碳纳米管并[b] - 碳纳米管[一个];\r
    });\r
    的console.log(排序);

\r

\r
\r

I'm looking for an elegant way of sorting an array by the occurrence of its elements.

For example, in:

['pear', 'apple', 'orange', 'apple', 'orange', 'apple']

the output should look like

['apple', 'orange', 'pear']

I have tried to loop through the array and save the occurrence in another temporary array, but this solution was quite bad.

解决方案

It would require two loops.

    var arr = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
    //find the counts using reduce
    var cnts = arr.reduce( function (obj, val) {
        obj[val] = (obj[val] || 0) + 1;
        return obj;
    }, {} );
    //Use the keys of the object to get all the values of the array
    //and sort those keys by their counts
    var sorted = Object.keys(cnts).sort( function(a,b) {
        return cnts[b] - cnts[a];
    });
    console.log(sorted);

这篇关于其元素的赋存数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆