首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取数组中元素的频率- JavaScript

获取数组中元素的频率- JavaScript
EN

Stack Overflow用户
提问于 2018-06-28 07:20:43
回答 1查看 221关注 0票数 0

刚刚检查了堆栈溢出,注意到这个问题可能还没有得到回答:如何获取给定数组中元素的出现- JavaScript

代码语言:javascript
复制
let array = [6, 1, 5, 1, 1, 8, 2, 4, 6, 0] // Elements in array

getOccurrence(array) /* returns
    [
        {occurrence: x, item: array[y]},
        {occurrence: ..., item: ...},
        {...},
    ]

    where 'x' is the frequency of an item in the array.a
*/

如果使用任何算法,这是可能的,请分享。

EN

回答 1

Stack Overflow用户

发布于 2018-06-28 07:31:58

我建议你这样做:

代码语言:javascript
复制
function getFrequencies(array) {
    // Create an object to store the frequencies of each item in our array.
    // We'll call it 'Frequencies'
    let frequencies = [],
        iterator = 0,
        length = array.length;

    // Index our array
    for (iterator; iterator != length; iterator += 1) {
        // Collect an item from our array and reset our Frequencies iterator
        let item = array[iterator],
            frequenciesIterator = frequencies.length;

        // If our item exists within our Frequencies
        if (
            (function() {
                // Iterate through our Frequencies object
                while (frequenciesIterator)
                    if (frequencies[frequenciesIterator -= 1].item === item)
                        return !0
            })()
        ) {
            // If the Frequencies iterator discovered a duplicate item from our Array
            // and Frequencies has already recorded the item
            if (frequencies.length > frequenciesIterator)
                // Increase the frequency of the recorded item
                frequencies[frequenciesIterator].occurrence += 1
        }

        else
            // Add the item to our Frequencies
            frequencies.push({occurrence: 1, item: item})
    }

    return frequencies
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51072688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档