按频率对 Javascript 数组进行排序,然后过滤重复 [英] Sort a Javascript Array by frequency and then filter repeats

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

问题描述

采用 javascript 数组、按值的频率排序,然后过滤唯一值的优雅方法是什么?

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

所以,

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

变成

["橘子、"香蕉"、"苹果"]

推荐答案

先计算每一项的频率.

{
    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 中新引入的数组函数) 并结合去重和频率图生成步骤,

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天全站免登陆