Locate and retrieve the item that appears most often in a given array

In order to determine the mode of an array consisting of integer numbers only, I must create a function named findMode. If the array is empty, the function should return 0. Otherwise, it should return the element that occurs most frequently in the array. In case there are multiple modes, the smallest value among them should be returned. To achieve this, I need to generate a new array to keep track of how many times each number appears in the input array.

Here is the initial implementation:

import { print } from "....";

export let main = async () => {
    let input = [2, 1, 1, 2, 1, 0]
    print(mode(input))

};

export let findMode = (b: number[]): number => {
    let newArr: number[] = []; /** An intermediate array created to store count */
    if (b.length === 0) {
        return 0;
    for (let i = 0; i < b.length; i++) {


};
main();

The expected/actual results are as follows:

If the array is [2,1,1,2,1,0], the expected result is 1. When inspecting the array with counts, newArr[1,3,2] should be printed. This signifies that element 0 appears once, element 1 appears thrice, and element 2 appears twice. The maximum occurrence corresponds to index 1 in the intermediate array, leading to the mode being 1.

For arrays like [0,0,0,1,1,2,1,1], [4,4,7,4,0,7], [-4,-4,-1,3,5], [1,1,2,3,2], and [10,10,10,20,20,30], the expected modes are 1, 4, -4, 1, and 10 respectively. In cases where there are multiple modes, the smallest one should always be selected.

Answer №1

Do you think a solution like this would be effective?

const calculateMode = (numbers: number[]): number => {
    // Array to store values and their counts
    const counts: Array<{ value: number, count: number }> = [];

    if (!numbers || !numbers.length) {
        return 0;
    }

    for (let i = 0; i < numbers.length; i++) {
        const val = numbers[i];
        const count = counts.find(count => count.value === val);

        if (count) {
            count.count++;
        } else {
            counts.push({ value: val, count: 1 });
        }
    }

    const mode = counts.sort((c1, c2) => c2.count - c1.count)[0];

    const largestNumber = counts.sort((c1, c2) => c2.value - c1.value)[0];
    let newArr = new Array(largestNumber);
    newArr = newArr.map((val, i) => {
        const count = counts.find(count => count.value === i);
        if (count) {
            return count.count;
        } else {
            return 0;
        }
    });
};

Answer №2

To solve this problem and get the desired result, you can utilize the Array#reduce method along with an additional object to keep track of counts.

export let findMode = (b: number[]): number => {
  // Object to store count of each element
  // Initialized with '0' with a count of 0 as default value
  let ref = {
    '0': 0
  };

  return b.reduce((value, num) => {
    // Set count to 0 if not defined
    ref[num] = ref[num] || 0;

    // Increase count for current element
    ref[num]++;
    
    // If the count of the current element is greater than the previous one
    // Return the current element
    if (ref[num] > ref[value]) {
      return num;
      
    // If counts are equal, return the smaller value
    } else if (ref[num] === ref[value]) {
      return num < value ? num : value;
    }
    
    // Otherwise, return the previous value
    return value;
    
    // Initialize the initial value as 0 (default)
  }, 0);
};

let findMode = b => {

  let ref = {
    '0': 0
  };

  return b.reduce((value, num) => {
    ref[num] = ref[num] || 0;
    ref[num]++;
    if (ref[num] > ref[value]) {
      return num;
    } else if (ref[num] === ref[value]) {
      return num < value ? num : value;
    }
    return value;
  }, 0);
};


[
  [2, 1, 1, 2, 1, 0],
  [1, 3, 2],
  [0, 0, 0, 1, 1, 2, 1, 1],
  [4, 4, 7, 4, 0, 7],
  [-4, -4, -1, 3, 5],
  [1, 1, 2, 3, 2],
  [10, 10, 10, 20, 20, 30]
].forEach(v => console.log(findMode(v)))

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

What is causing the issue with TypeScript's React.createRef() and its compatibility with the material-ui Button element?

Running on React version 16.13.1, my component class includes a Material-UI Button component and a RefObject to access the button element. class Search extends React.Component<any, any>{ constructor(props: any) { super(props) this.streetV ...

Why does VSCode open a React app in Edge instead of Chrome?

Recently, I began a new project using the react-create-app template with typescript. However, when I run npm run dev, it unexpectedly opens in the Edge browser instead of Chrome. Does anyone know how to make it open in Chrome instead? ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

In Angular, I aim to invoke the this.addDispatchToReceive method whenever the outcome is successful within each forEach iteration

How can I ensure that the values from this.stockItemDispatch are obtained in this.addDispatchToReceive(); during each iteration of a loop, instead of only getting the last stock value? The issue is that the subscribe function runs after the foreach cycle ...

Redux does not have the capability to insert an object into an array

I'm currently learning about redux and I've encountered an issue trying to add multiple objects into the initialState array. I attempted using the push() method, but it isn't working as expected. The submitter value is being passed to my act ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

Tips on rearranging an array by using keys from a different array?

Can you suggest a method to rearrange an array based on values in another array? The array that needs re-ordering: Array ( [0] => Array ( [full_name] => Graham Smith ) [1] => Array ( [full ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Cannot locate: Unable to find the module '@react-stately/collections' in the Next.js application

While working on my Next.js app, I decided to add the react-use package. However, this led to a sudden influx of errors in my Next.js project! https://i.stack.imgur.com/yiW2m.png After researching similar issues on Stackoverflow, some suggestions include ...

Ways to compare UTC timestamps using JavaScript

Insight into Time Data I have obtained UTC start and end times from a database query, which are stored in an array format as follows: [ '9145001323', '08:00', '12:00' ] The second and third elements in the array indicate t ...

"Encountered a problem when trying to access properties within a

Struggling to access properties of a nested object in TypeScript while using Angular, I encountered the following error: Object is possibly 'undefined'. Here is the code snippet: export interface Address{ city?: string; neighborhood?: string; } ...

There is a clash between the webpack-dev-server package and its subdependency, the http-proxy-middleware

Awhile back, I integrated webpack-dev-server v3.11.0 into my project, which - upon recent inspection - relies on http-proxy-middleware v0.19.1 as a dependency. Everything was running smoothly until I separately installed the http-proxy-middleware package a ...

Substitute a value in a list with a distinctive identification code

I have a list of dailyEntries. Each entry has a unique identifier called id. I am given an external dailyEntry that I want to use to replace the existing one in the array. To achieve this, I can use the following code: this.dailyEntries = this.dailyEntri ...

Using a functional wrapper component to reset the modal field in Reactstrap upon closing and reopening

In the main component that displays a list of to-do tasks, we have the ability to add or edit existing tasks. To facilitate this functionality, a separate wrapper was created. import React, { useEffect, useState } from 'react'; import { Label ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

How can you toggle the selection of a clicked element on and off?

I am struggling with the selection color of my headings which include Administration, Market, DTA. https://i.stack.imgur.com/luqeP.png The issue is that the selection color stays on Administration, even when a user clicks on another heading like Market. ...

"Using a PHP array with Highcharts for dynamic data visualization

I am having difficulty inserting values into the array at specific positions. I want to create an empty array, retrieve data from the database, and based on whether they are global or local, populate the PHP array as shown below. However, I'm facing c ...