Is there a method to distinguish between different types of array keys in JavaScript? For instance, comparing arr[1] with arr["1"]

I was attempting to solve a common problem involving finding the most popular item in an array.

While I came across some O(n) solutions using maps, none seemed to work effectively when dealing with mixed data types such as:

[1,2,1,3,"1","a"]

The issue arises when "1" is considered equal to 1. Is there any way to customize comparison within JS? Or is there an O(n) solution that can address this?

The focus here is on finding the most frequent element in the array, bearing in mind that there may be multiple elements with the same frequency:

function getMostFrequent(array) {

    if (array.length == 0)
        return null;

    let mapEl = {};
    let maxEl = [];
    let maxCount = 1;

    for (let i = 0; i < array.length; i++) {
        let el = array[i];

        if (mapEl[el] == null) {
            mapEl[el] = 1;
        } else {
            mapEl[el]++;
        }

        if (mapEl[el] > maxCount) {
            maxCount = mapEl[el];
            maxEl = [el];
        } else if (mapEl[el] === maxCount) {
            maxEl.push(el);
        }

    }

    console.log(maxEl);
    return maxEl;
}

Answer №1

Here are some O(n) solutions that utilize maps

Maps are suitable for this task because map "keys" can have a variety of types, such as numbers, strings, and objects (with distinctions):

const input = [1,2,1,3,"1", "1", "1", "a"];
const map = new Map();
input.forEach(key => map.set(key, (map.get(key) || 0) + 1));
console.log(
  [...map.entries()].reduce((a, b) => b[1] > a[1] ? b : a)
);

You could also opt for using reduce, which may be more fitting in this context:

const input = [1,2,1,3,"1", "1", "1", "a"];
const map = input.reduce(
  (map, key) => map.set(key, (map.get(key) || 0) + 1),
  new Map()
);
console.log(
  [...map.entries()].reduce((a, b) => b[1] > a[1] ? b : a)
);

Indeed, these solutions run in O(N) time complexity.

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

Create an interactive HTML table featuring objects as the selected values

I have been attempting to generate an HTML table that is filled with objects. The goal was to make the table selectable by row (via hover), triggering a function when the row is hovered over. Here are the table headers stored in an array: var topTitles ...

Error 404 in Angular HTTP Request

I'm encountering a 404 error while attempting to send a post request, along with a 'possibly unhandled rejection' error. Given my limited experience with Angular, any advice would be greatly appreciated. I've gone through the documentat ...

The issue of setTimeout malfunctioning when used in conjunction with ajaxStart

I am looking to optimize the appearance of my loading animation during an ajax request by delaying it and ensuring it only shows if the request lasts longer than a second. However, I am facing an issue where even though the delay is set at more than 80 i ...

Turning a text input field into a functional button

I am attempting to create a function that will read the text from a text area, convert it into a string, and display it somewhere on the page. I'm expecting it to show up within the paragraph with the id "biljeske", but currently nothing is being disp ...

Is create-react-native-app experiencing functionality issues?

As someone who is new to expo and create-react-native-app, I recently encountered a strange issue while learning react-native. Normally, I use create-react-native-app without any problems. However, one day when I tried to create a new project, I was presen ...

Material-ui library causing complications in rendering React components

Encountering an issue with React and the material-ui library – my cards are displaying vertically instead of horizontally aligned side by side. Though I attempted to adjust the react grid component, it did not resolve the problem. Current Output: https: ...

Best practices for structuring npm scripts and multiple webpack configurations

My project consists of multiple dashboards, and I've decided to create separate scripts in my package.json for each one. Building all the dashboards during development when you only need to work on one can be time-consuming. So, I discovered that it&a ...

Add more key value pairs to another <div> element

My setup involves radio buttons attached to div elements. When a div is clicked, the information displayed on the widget updates to show the data associated with that div. I am using the Yahoo API to fetch the data in JSON format. The correct data is being ...

An extremely basic inquiry regarding JavaScript form validation

Is there a way to add a simple icon next to a form field when users type in their name or email address? I only want the icon to show if even one character is typed. The icon should change based on whether the field has content (success) or not (fail). L ...

Sort columns in DataTables.js that contain HTML links with numerical text

Is there a way to sort columns in DataTables.js that contain HTML anchor tags with numerical values, like <a href="#">123</a>? I'm looking to sort these columns numerically. I've looked at the DataTables HTML sorting auto-detection e ...

An error occurred with Next.js and Lottie where the property "completed" could not be added because the object

Encountering an issue with Lottie's animation. Attempting to retrieve a JSON file (Lottie Animation) from Contentful and display it using the Lottie Component. However, facing an error message: "TypeError: Cannot add property completed, the object is ...

Is it possible to execute NodeApp in a command-line fashion?

NodeApp's NLContext has the capability to interpret JavaScript using evaluateScript. Additionally, it also supports argv and env: Current functionalities: process: .argv, .env, .exit(), .nextTick() How can NodeApp be executed in a command-like man ...

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

Python's way of managing callback functions within a single line

My goal is to create a Python function that can traverse a data structure and perform a specified operation at each step using a provided callback function. To better illustrate this concept, consider the following simple example: def find_min_value(lst): ...

Do commas at the end of JSON objects pose a risk of breaking

After diving into the proposed JavaScript features, one that caught my attention is the idea of supporting trailing commas in object literals and arrays. When it comes to parameters, trailing commas are not relevant, so let's put that aside for now. ...

Rendering implemented in an Angular component through Three.js

Currently immersed in developing a dynamically generated three.js component within Angular. The statically created Plot3dComponent (via selector) functions flawlessly. However, encountering difficulties in rendering the component dynamically using Componen ...

Utilize AJAX response to mark checkbox as checked

I have an HTML checkbox that I am attempting to check using a script received as an ajax response. Below is my HTML snippet: <form class="form-vertical sms-settings-form"> <div class="form-group"> <div data-toggle="tooltip" titl ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Using MaterialUI to create a GridListTile with two IconButtons

I'm working with a GridListTile and trying to add a second button, but I'm having trouble getting both buttons to display. Even though I've attempted to include two ActionIcons, only one of them is showing up. Here's the code snippet: ...

Alternate. (individually)

Issue with Running Program I've been struggling to get my program to run correctly. The task at hand is to have the program display only one question at a time. But no matter what I try, clicking on all questions displays all the answers simultaneous ...