Retrieve all elements from an array that have the highest frequency of occurrence

Consider an array like [1,4,3,1,6,5,1,4,4].

The element with the highest frequency in this array is 3. The goal is to select all elements from the array that have a frequency of 3, so in this case we would select [1,4].

To achieve this, one possible method is shown below:

var count = {}, array=[1,4,3,1,6,5,1,4,4], value;
 for (var i = 0; i < array.length; i++) {
            value = array[i];
            if (value in count) {
                count[value]++;
            } else {
                count[value] = 1;
            }
        }
console.log(count);

This code snippet provides the frequency of each element in the array. We then need to identify which elements have the highest frequency.

Answer №1

To tackle this issue, I suggest the following approach.

Begin by outlining how you believe the problem can be resolved IN ENGLISH, or a similar language (or your mother tongue of course!). Document each step. Start with a general overview, like:

  1. Determine the frequency of each element in the input.

  2. Identify the highest frequency.

and so forth. It is crucial at this stage not to get caught up in implementation specifics. Your solution should be adaptable to nearly any programming language.

Subsequently, elaborate on each step by including substeps. For example, you could write:

  1. Identify the highest frequency.

    a. Assume the highest frequency is zero.

    b. Evaluate each frequency. If it exceeds the current highest frequency, update it as the new highest frequency.

Validate your algorithm by mentally executing it yourself.

Then, transform what you have documented into what is often referred to as pseudo-code. At this point, our algorithm begins to resemble a basic computer program, yet remains easily comprehensible to humans. We can now utilize variables to symbolize elements. For instance, we may write "max_freq ← cur_freq". We can mention arrays and compose loops.

Lastly, convert your pseudo-code into JS. If all goes smoothly, it should function correctly from the start!

In recent times, many individuals are diving straight into JavaScript without understanding how to analyze algorithms, even elementary ones. They mistakenly believe that they must have the ability to conjure JS effortlessly, as if speaking in tongues. However, proficient programmers do not immediately resort to writing array.reduce upon encountering a problem; they always go through the process--even if only mentally--of considering the approach to the problem, a practice worth emulating.

If you fail to master this skill, you will spend your entire career turning to sites like SO whenever you struggle to comprehend a problem.

Answer №2

An approach using Array.prototype.reduce() to create a temporary object named count, Object.keys() for obtaining the keys of the temporary object, leveraging Array.prototype.sort() method for arranging the count results, and utilizing Array.prototype.filter() to extract the top values with the highest count.

Edit: Shout-out to @Xotic750 for ensuring the original values are preserved.

var array = [1, 4, 3, 1, 6, 5, 1, 4, 4],
    result = function () {
        var temp = array.reduce(function (r, a, i) {
            r[a] = r[a] || { count: 0, value: a };
            r[a].count++;
            return r;
        }, {});
        return Object.keys(temp).sort(function (a, b) {
            return temp[b].count - temp[a].count;
        }).filter(function (a, _, aa) {
            return temp[aa[0]].count === temp[a].count;
        }).map(function (a) {
            return temp[a].value;
        });
    }();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Bonus feature with an alternative approach

var array = [1, 4, 3, 1, 6, 5, 1, 4, 4],
    result = array.reduce(function (r, a) {
        r.some(function (b, i) {
            var p = b.indexOf(a);
            if (~p) {
                b.splice(p, 1);
                r[i + 1] = r[i + 1] || [];
                r[i + 1].push(a);
                return true;
            }
        }) || (
            r[1] = r[1] || [],
            r[1].push(a)
        );
        return r;
    }, []).pop();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №3

Check out this code snippet:

var input = [1,4,3,1,6,5,1,4,4];

var output = {};

for ( var counter = 0; counter < input.length; counter++ )
{
   if ( !output[ input[ counter ] ] )
   {
      output[ input[ counter ] ] = 0;
   }
   output[ input[ counter ]]++;
}

var outputArr = [];
for (var key in output)
{
  outputArr.push([key, output[key]])
}
outputArr = outputArr.sort(function(a, b) {return b[1] - a[1]})

The initial values of outputArr now represent the elements with the highest frequency.

You can view this onJSFiddle

For the desired output, check the updatedJSFiddle

var input = [1,4,3,1,6,5,1,4,4];

var output = {}; 

for ( var counter = 0; counter < input.length; counter++ )
{
   if ( !output[ input[ counter ] ] )
   {
      output[ input[ counter ] ] = 0; 
   }
   output[ input[ counter ] ]++; 
}
var outputArr = [];
var maxValue = 0;
for (var key in output)
{
  if (  output[key] > maxValue )
  {
    maxValue = output[key]; 
  }
  outputArr.push([key, output[key]])
}
var finalArr = []; 
for ( var counter = 0; counter < outputArr.length; counter++ )
{
  if ( outputArr[ counter ][ 1 ]  == maxValue )
  {
     finalArr.push( outputArr[ counter ][ 0 ] )
  }
}

console.log( finalArr );

Answer №4

In order to achieve the desired outcome, I suggest implementing a solution similar to this one. Please note that this code snippet is not tested, but it includes comments to aid in understanding my approach.

// Define an array
var initial_array = [1,4,3,1,6,5,1,4,4];

// Initialize a counter object
var counter = {};

// Iterate through the array
initial_array.forEach(function(item){

    // Check if the element is already counted
    if (counter.hasOwnProperty(item)){
        counter[item] += 1;
    } else {
        counter[item] = 1;
    }
});

// Now counter = {1 : 3, 4 : 3, 3 : 1, 6 : 1, 5 : 1}

// Convert object keys to an array for easier sorting
var sortable = [];

for (var element in counter){
    sortable.push([element, counter[element]]);
}

// After sorting, sortable = [ [1,3], [4,3], [3,1], [6,1], [5,1] ]

// Sort the list
sortable.sort(function(a, b) {return a[1] - b[1]})

// Once sorted, sortable = [ [1,3], [4,3], [3,1], [6,1], [5,1] ]

// The elements with higher frequencies will be at the beginning of the list

// Keep track of the highest frequency
highest = 0;

// Store the final results here
results = [];

// Traverse the sorted list from highest frequency downwards
sortable.forEach(function(item){

    // As the list is sorted, compare frequencies to find the highest
    if (item[1] >= highest){

        highest = item[1];
        results.push(item[0]);

    }

});

Answer №5

I completely agree with the sentiments shared by @torazaburo.

ES6 is starting to win me over as it gradually becomes more prominent in my daily browsing experience. I've implemented a solution using ES6 that is currently functioning smoothly in my browser.

The utilization of shims is essential for rectifying browser bugs and deficiencies, making it a recommended practice across all environments.

'use strict';
// Array containing values
const array = [1, 4, 3, 1, 6, 5, 1, 4, 4];
// Using an ES6 Map to track value frequencies
const frequencies = new Map();
for (let item of array) {
  frequencies.set(item, frequencies.has(item) ? frequencies.get(item) + 1 : 1);
}
const groups = [];
for (let item of frequencies) {
  const value = item[0];
  const frequency = item[1];
  if (groups[frequency]) {
    groups[frequency].push(value);
  } else {
    groups[frequency] = [value];
  }
}
const mostFrequent = groups.pop();
document.getElementById('out').textContent = JSON.stringify(mostFrequent);
console.log(mostFrequent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.0/es6-shim.js"></script>
<pre id="out"></pre>

Answer №6

If you want to determine the frequency of each number in an array, you can use the following approach:

const numbers = [1, 4, 3, 1, 6, 5, 1, 4, 4];

const frequency = numbers.reduce(function(counts, num) {
  if (counts[num]) {
    counts[num] += 1;
  } else {
    counts[num] = 1;
  }
  return counts;
}, {});

console.log(frequency);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

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

Generating unique ID's for data posting in PHP and JavaScript

I've developed a dynamic form that includes an "add more" button to generate an XML file for data import purposes. Users can fill out the form and add as many entries as needed by clicking on the "add more" button. The inputted data is then processed ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Divide the string by spaces

One of the challenges I am facing involves a textarea where users can input messages. The goal is to split the message into an array of words after detecting an '@' symbol, and then search for specific words in that array such as @person1 and @pe ...

Creating a function in JavaScript to return an Unsubscribe and Array from a Firebase Snapshot Listener in Svelte

In my SvelteKit project, I have integrated Firebase Firestore. I maintain a db.js file that contains various functions utilized in Svelte components. One such function is detailed below. export const Items = { async getMany() { let dbRef = db.c ...

Determining Cost Using Quantity and Option Changes in Angular 4

Task In the shopping cart, there is a list of items with options, quantities, and prices. The goal is to calculate the total price based on any changes in the quantity and option of an item. Investigation I included [(ngModel)] for 2-way data binding, ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

Encountering an Issue while Deploying a create-react-app to Heroku

Despite trying various online remedies, I am still encountering an error while attempting to deploy a simple React.js app on Heroku. The app successfully builds when I execute git push heroku master, but upon opening it, I consistently receive an applicati ...

Click on the div to add items from an array into it

I have a unique set of lines stored in an array: var linesArr = ["abc", "def", "ghi"]; In my JavaScript, I dynamically create and style a div element using CSS: var div = document.createElement("div"); div.className = "storyArea"; div.in ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

How to address critical vulnerabilities found in a Vue.js project that relies on the 'vue-svg-loader' dependency, specifically impacting 'nth-check', 'css-select', and 'svgo'?

Attempting to launch a Vue version 2 project, encountered the following error: # npm audit report nth-check <2.0.1 Severity: high Inefficient Regular Expression Complexity in nth-check - https://github.com/advisories/GHSA-rp65-9cf3-cjxr fix available ...

Mirror Image Iframes

Currently, I have been tasked with constructing a side-by-side "frame" using HTML. The idea is that when the content in the iframe on the left is selected, it will appear in the iframe next to it on the same page. Here's some additional context: The ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Exploring the process of retrieving MongoDB documents with methods such as findOne() or find() in Node.js, particularly when the models and schema are contained in a separate file

As someone who is new to node, MongoDB, and coding in general, I'm currently working on a project involving the creation and storage of documents in MongoDB using Mongoose. Initially, all my models and schemas were housed in the app.js file, allowing ...

Leverage AngularJS $http.get method to continuously fetch JSON array upon scrolling

Here is a snippet of code that utilizes AngularJS to retrieve a JSON response. I am looking for assistance in implementing a functionality where the page should make additional requests when the user scrolls to the bottom, continuing until the JSON array ...

Unable to showcase information in the center of an HTML document

Hello, I'm facing an issue with my HTML page that has a left vertical nav-bar. Despite my efforts, I can't seem to display content (text) in the center of the page as shown in the screenshot with the red oval. I've attempted inserting text ...

Display a custom AngularJS directive on content loaded through $http request

I'm facing a dilemma. I have created a directive app.directive('a', function() { return { restrict: 'E', link: function(scope, elem, attrs) { elem.on('click', function(e){ ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

Is there a way to eliminate currency within an Angularjs directive?

Currently, I am utilizing a directive to properly display currency format. You can find the directive at this URL: http://jsfiddle.net/ExpertSystem/xKrYp/ Is there a way to remove the dollar symbol from the output value and only retain the converted amoun ...

Using Jackson to extract array objects from a JSON array without keys and parsing them

My current challenge involves parsing a JSON array that includes an inner list of arrays without any keys. The issue arises when I attempt to deserialize the JSON array as it throws an exception during runtime: com.fasterxml.jackson.databind.JsonMappingEx ...