0

just checking Stack Overflow and noticed that this question may have not been answered yet: How to get the occurrences of elements in a given array - 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
*/

If this is possible using any algorithms, please share.

Lapys
  • 936
  • 2
  • 11
  • 27

1 Answers1

0

I suggest you go about it this way:

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
}
Lapys
  • 936
  • 2
  • 11
  • 27