Discover the most frequently repeated elements in a JavaScript array

I'm working with an array that contains multiple names such as:

[mike, bob, john, john, rick, bob]
Could anyone advise on the most efficient method to determine which name appears the most frequently?

Answer №1

Create an object with a count attribute by utilizing the Array#reduce method. Afterwards, arrange the array of property names (obtained with the help of Object.keys method) based on the count using the Array#sort method and ultimately retrieve the first element.

var exampleArr = ['mike', 'bob', 'john', 'john', 'rick', 'bob'];

// create an object to store the count
var object = exampleArr.reduce(function(o, v) {
  // check if the property is defined
  o[v] = o[v] || 0;
  // increment the count
  o[v]++;
  // return the object
  return o;
  // initialize as an empty object
}, {});

// sort by count in descending order and get the first element
console.log(
  Object.keys(object).sort(function(a, b) {
    return object[b] - object[a];
  })[0]
)

// alternatively, use reduce to find the property with the highest count
console.log(
  Object.keys(object).reduce(function(a, b) {
    return object[b] > object[a] ? b : a;
  })
)

Answer №2

To efficiently find duplicates within a list in linear time complexity O(n), one common approach is to iterate through the list and add each item to a set. Before adding an item, check if it already exists in the set. If it does, then that item is a duplicate.

names = ['mike', 'bob', 'john', 'john', 'rick', 'bob'];

seen = new Set();

names.forEach(function(item, index, array) {
    if (seen.has(item)) {
        console.log(item + " is a duplicate");
    } else {
        seen.add(item);
    }
});

Another method is to sort the list in O(n log(n)) time complexity, saving on extra space usage. While iterating over the sorted array, compare pairs of elements to identify duplicates:

names = ['mike', 'bob', 'john', 'john', 'rick', 'bob'];

names.sort().forEach(function(item, index, array) {
    if ((index > 0) && (array[index - 1] == item)) {
        console.log(item + " is a duplicate");
    }
});

Answer №3

def find_duplicates(lst):
   seen = set()
   for item in lst:
      if item in seen:
        print(item)
      seen.add(item)
      
find_duplicates(['mike', 'bob', 'john', 'john', 'rick', 'bob'])

Answer №4

To utilize the map function, you can do the following:

function findDuplicates() {
     var name, names = ['mike', 'bob', 'john', 'john', 'rick', 'bob'];
     var map = new Map();
     var max = 1;
     var maxRecurringString = "";
        for(name of names) {
    
           if(map.get(name) === undefined) {
              map.set(name, 1);
           } else {
              var count = map.get(name);
              count = count+1;
              map.set(name, count);
                  if(max < count) {
                     max = count;
                     maxRecurringString = name;
                  }
            }
     }
    console.log("Maximum recurring string is ", maxRecurringString, ". Max number of times :" + max);
}
findDuplicates();

This code snippet displays the first string that appears the most number of times. For instance, in the example provided above, both bob and john appear twice. If you wish to print all strings that appear the maximum number of times, you can iterate through the map where the count matches the max count.

Answer №5

If you want to optimize your code for performance, the most efficient approach is to iterate through the array only once.

Avoid using Array#reduce, Array#sort, and Array#forEach as they will loop over the entire array, impacting performance especially with large datasets.

var findHighestRecurring = function(arr) {
    arr.sort();

    var i        = arr.length;
    var max      = { item:"", count: 0 };
    var last     = { item:"", count: 0 };
    var validate = function() {
        if (last.count > max.count) {
            max.item  = last.item;
            max.count = last.count;
        }
    }

    while (i--) {
        var curr = arr[i];

        if (last.item !== curr) {
            validate();
            
            last.item  = curr;
            last.count = 0;
        }
        
        last.count++;
    }

    validate();

    return max;
}

var sample = ["mike","bob","john","bob","john","rick","bob"];
var result = findHighestRecurring(sample);

console.log(result);

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

Discover how to extract the value from the server side during document.ready using jQuery without the need for any specific event

In my project, I'm facing a requirement where I need to fetch a value from server-side code using any event and utilize it to create a dialog box. Initially, I attempted to retrieve the value in window.onload but discovered that window.onload is trigg ...

Eliminating the data type from the array of JSON entities

In my Node.js project, I have defined a class as follows: let id; let totalCalls; let totalMinutes; class CallVolume { constructor(id){ this.id = id; this.totalCalls = 0; this.totalMinutes = 0; } } module.exports = CallVolume ...

Set the style properties of one class to match the style properties of another class using JavaScript

I need to dynamically create a div using the Bootstrap panel for displaying it. The div's class will either be "panel panel-success" or "panel panel-danger" based on the server response, which can be either "success" or "failure." To assign the class ...

Conditionally rendered components in JavaScript may cause the element.contains method to return false

I'm currently working on a form selector component and my goal is to have the dropdown element close whenever a user clicks anywhere else on the screen. This component has the following design: export const FormSelect = ({ defaultText, disabled, ...

Enlarging an image on canvas and creating a repeating pattern

My canvas size is 500px x 500px. I have a png image that matches the canvas size, which you can view here. I am looking to resize the image to 100px x 100px and then use it as part of a repeat pattern on the canvas. This is how I achieve this: // First d ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

Can an object in Node.js be 'required' to have access to the global scope of the importing files?

I've been researching extensively to find out if this is achievable. According to my findings so far, it seems that it may not be possible. Within my main.js file, I have the following code snippet: var commands = require('./commands.js'); ...

Autocomplete Dropdown failing to select default value when defaultValue option is set

stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data const [selectedNamesState, setSelectedNamesState] = useState([]); const transformedNpaData ...

Is it possible to retrieve the var name from an interpolated expression using template literals?

Suppose I have a variable like this: myVar = `Some text with ${eggs} and ${noodles} or ${pies}`; Is there a method to obtain myVar as an unprocessed string prior to variable substitution, essentially "Some text with ${eggs} and ${noodles} or ${pies}"? M ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

What could be the reason behind the malfunctioning of a custom filter in this specific Vue 3 application?

In my development project, I am creating a Vue 3 CRUD application for managing Users. The goal is to display the users in reverse order so that the newest additions appear at the top. To achieve this, I have implemented a custom filter as shown below: reve ...

Having trouble getting the if statement to work for a basic JavaScript toggle feature

The functionality implemented in the resize() function involves checking for the presence of the switch class on the body element. If the class is present, it is removed upon firing the resize function; otherwise, the class is added. However, a problem ar ...

Preventing mouse controls from moving the cube: a gift/page2 tutorial

(gift/page2) in this snippet: You can observe a demonstration of a red cube rotating on the web page. However, my goal is to prevent the cube from being manipulated by the mouse or fingers on an iPad. I want the cube to remain stationary in its position. ...

Is there a way to bring to life the addClass() and removeClass() jQuery functions through animation?

I am currently developing a website and I want to be able to toggle the visibility of sections by using the ".hidden" bootstrap class within click events. Here is the basic code snippet: $('selector').click(function(){ $('*part-to-hi ...

Why is ReactCSSTransitionGroup creating numerous components when I am anticipating just one?

While experimenting with ReactCSSTransitionGroup for animations, I encountered a peculiar situation that doesn't quite add up in my understanding. In the scenario below, every time I click on <div className="HeartControl">, it updates the heigh ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

Unable to locate template or render function for Vue Draggable Next component

Looking to incorporate Vue Draggable Next into a Vue 3 example page but encountering some challenges. I've attempted to follow the instructions in the repository. However, I ran into issues when importing the Vue Draggable Next component and had to re ...

Find the frequency of a specific string within a JSON array

My current task involves working with a stringified array: JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","resti ...

Adjusting the Height of a Div Using a Single Button

Seeking help to make a div expand and then shrink with one button click. I've tried various methods but the div won't change size. Can someone guide me on why this is happening? Here is the code, CSS, and HTML for my latest attempt: $("dasButto ...