Finding the occurrences of elements in an array using JavaScript

While browsing Stack Overflow, I stumbled upon a question that has yet to be answered: How can I count the occurrences of elements in a specific array using 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.
*/

If there are any algorithms that can achieve this, please advise.

Answer №1

Here is a suggested approach for solving this problem:

function findItemFrequencies(arr) {
    let frequencies = [],
        iterator = 0,
        len = arr.length;

    for (iterator; iterator != len; iterator += 1) {
        let item = arr[iterator],
            freqIterator = frequencies.length;

        if (
            (function() {
                while (freqIterator)
                    if (frequencies[freqIterator -= 1].item === item)
                        return !0
            })()
        ) {
            if (frequencies.length > freqIterator)
                frequencies[freqIterator].occurrence += 1
        }

        else
            frequencies.push({occurrence: 1, item: item})
    }

    return frequencies
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to identify whether a div is in view and includes an input field

This is a unique question that is not related to the issue of querySelectorAll detecting value in input. Instead of asking whether an input field has a value, I am interested in how to detect if the current visible div contains an input field. This is a n ...

Unable to use Office.context.mailbox.item.displayReplyAllForm with attachments on outlook.live.com as well as receiving internal server errors when using the Outlook API

When using office.js outlook add-ins, the displayReplyAllForm with attachments function is opening the reply form without attachments in outlook.live.com. However, it works perfectly fine in outlook.office.com. Is there any workaround for this issue? Off ...

Tips on capturing a URL using JQuery

Currently, I am in the process of importing an external HTML file into my webpage. Within this file, there is a JavaScript method linked to a form submission event. function ValidateInput(){ //some code if(validationFailed){ ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

Group the elements of the second array based on the repeated values of the first array and combine them into a single string

I have a challenge with two arrays and a string shown below var str=offer?; var names = [channelId, channelId, offerType, offerType, Language]; var values =[647, 763, international, programming, English]; Both arrays are the same size. I want to creat ...

Conceal the scrollbar and enable horizontal swiping using CSS

I have set up a container where I want the content to scroll horizontally from left to right on mobile devices, and I would like to be able to swipe to navigate while hiding the scrollbar. You can view the implementation on this JSfiddle link Do you think ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

Executing a jQuery post request without utilizing AJAX or a form

Is there a method in jquery to perform a post submission without using a form? For example, can I utilize the function $.post("script.php",{var1:"abc", var2: "cde"}) in a way that rather than running in the background, it will actually submit the values ...

The process of integrating a Loader in Javascript

I am in need of a simple "page loading" animation while my photo is being uploaded. Unfortunately, when I tried using the "blockUI" JavaScript for this purpose, it didn't seem to work with my form. For uploading the image, I have employed a div as a ...

Fixing the Bootstrap Datepicker: A Step-by-Step Guide

Is there a way to configure the Datepicker to display today's date and tomorrow's date? Click here for the JS file Check out the image on our website https://i.stack.imgur.com/VyFUB.jpg ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

Is the div empty? Maybe jQuery knows the answer

I currently have a <div id="slideshow"> element on my website. This div is fully populated in the index.php file, but empty in all other pages (since it's a Joomla module). When the div is full, everything works fine. However, when it's emp ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

It seems that the maximum call stack size has been exceeded, resulting in a

Within this dropdown, I have incorporated a checkbox containing values in the form of an object. (refer to attached image) Every time I make a selection from the dropdown, there is a watch function that updates this new value, which is essentially an arra ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

The AngularJS directive "ng-include" is used to dynamically

I am encountering an issue with ng-include not retrieving the file. What could be the reason for the problem in accessing a property from a link within ng-include? I would appreciate any assistance with resolving this matter. (function(){ var app = angu ...

Exploring the capabilities of mongojs: Adding items to arrays within fields

I've been researching extensively on this subject, but I'm completely stumped. Here's my dilemma (I'm working with node.js and mongojs): I want to create documents like the following: { "_id" : ObjectId("50ce2f7f98fa09b20d000001" ...

Working with Ext JS: Dynamically adjusting panel size when the browser window is resized

I am facing an issue with a side panel in Ext.js. Everything is working fine until I resize the browser, at which point some components of the panel get cut off. https://i.sstatic.net/eaEGI.png Is there a way to make the panel resize automatically when t ...