按频率JavaScript数组,然后筛选重复 [英] Sort a Javascript Array by frequency and then filter repeats

查看:204
本文介绍了按频率JavaScript数组,然后筛选重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是采取了JavaScript数组,由值的频率顺序,然后筛选的唯一身份优雅的方式?

What is an elegant way to take a javascript array, order by the frequency of the values, and then filter for uniques?

因此​​,

[苹果,橙子,橙子,橙子,香蕉,香蕉,橘子]

变为

[橘子香蕉,苹果]

推荐答案

首先计算每个项目的频率。

Compute the frequency of each item first.

{
    apples: 1,
    oranges: 4,
    bananas: 2
}

然后创建一个从这个频率对象也将删除重复的数组。

Then create an array from this frequency object which will also remove the duplicates.

["apples", "oranges", "bananas"]

现在排序此数组中使用我们先前创建的频率图降序排列。

Now sort this array in descending order using the frequency map we created earlier.

function compareFrequency(a, b) {
    return frequency[b] - frequency[a];
}

array.sort(compareFrequency);

下面就是整个源(使用新引进的阵列功能ECMA 5 的),并结合德-duplication和频率地图生成步骤,

Here's the entire source (using the newly introduced Array functions in ECMA 5) and combining the de-duplication and frequency map generation steps,

function sortByFrequency(array) {
    var frequency = {};

    array.forEach(function(value) { frequency[value] = 0; });

    var uniques = array.filter(function(value) {
        return ++frequency[value] == 1;
    });

    return uniques.sort(function(a, b) {
        return frequency[b] - frequency[a];
    });
}

同上使用规则阵列迭代

Same as above using the regular array iteration.

function sortByFrequencyAndRemoveDuplicates(array) {
    var frequency = {}, value;

    // compute frequencies of each value
    for(var i = 0; i < array.length; i++) {
        value = array[i];
        if(value in frequency) {
            frequency[value]++;
        }
        else {
            frequency[value] = 1;
        }
    }

    // make array from the frequency object to de-duplicate
    var uniques = [];
    for(value in frequency) {
        uniques.push(value);
    }

    // sort the uniques array in descending order by frequency
    function compareFrequency(a, b) {
        return frequency[b] - frequency[a];
    }

    return uniques.sort(compareFrequency);
}

这篇关于按频率JavaScript数组,然后筛选重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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