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

时间:2018-06-27 23:20:43

标签: javascript arrays

仅检查堆栈溢出,并注意到可能尚未回答以下问题:如何获取给定数组中的元素-JavaScript

http://localhost:8080/

如果可以使用任何算法来实现,请分享。

1 个答案:

答案 0 :(得分:0)

我建议您这样处理:

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
}