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

Activate function on Ctrl + K in a React TypeScript project

I am currently developing a React TypeScript application using version v18.2.0. My goal is to trigger a function when the user simultaneously presses Ctrl + K. Here is the code snippet within my component: const keyDownHandler = (event: KeyboardEvent) =& ...

Creating an enumeration within a class

I'm encountering difficulties when trying to declare an enum element within a class. Despite attempting various methods to declare the enum, I am unable to make it function properly. Here is the (non-functional) class: export class Device extends El ...

Encountering a problem while compiling the Next.js app

Whenever I execute the command npm run build for a Next.js project (built with React and TypeScript), I encounter the following error: Error: Missing "key" prop for element in array react/jsx-key This issue is specifically related to the following piec ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

What is the best way to create an interface that only allows keys to be a combination of values from a specific property found within each object of an array?

interface Filter { id: string; name: string; } type Filters = Filter[]; const filters = [{ id: 'f1', name: 'f1name'}, { id: 'f2', name: 'f2name'}] interface State { ... } const state = { f1: any, ...

Obtain a byte array from an AngularJs controller

In my Angular controller, I am working with a byte array. When the download button is clicked in the view, I want to trigger the browser's download/saveAs dialog with 'report.pdf' as the pre-populated filename and PDF as the file type. After ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Exploring the Worldwide Influence of TypeScript, React, and Material-UI

I am currently following an official tutorial on creating a global theme for my app. In my root component, I am setting up the global theme like this: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme ...

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Expanding form fields dynamically with AngularJS

I am currently working on a form that allows users to click a '+' sign in order to add new lines. I've set up a function to be called when the button is clicked, which should push a new line into the array. However, for some reason the new l ...

Angular 10 introduces a new approach to handling concurrency called "forkJoin"

Here is the code I have: async getBranchDetails() ----component method { let banks = this.bankDataService.getBanks(); let branchTypes = this.branchDataService.getBranchTypes(); forkJoin([banks,branchTypes]).subscribe(results => { ...

Changing an object into an array for saving and transforming it back to an array for usage in JavaScript

I am dealing with a unique situation where I have an object created from dynamic checkboxes in Angular. The structure of the object looks like this: {"United States":true,"Canada":true,"Australia":false} While this format works well for storing values, I ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

What are the steps to splitting an array into separate integer and string arrays?

Can I split an array into two separate arrays containing strings and integers? Given Array: [ 0 => "4" 1 => "8" 2 => "15" 3 => "16" 4 => "23" 5 => "42" 6 => "apple" 7 => "water" ] Integer Array: [ ...

What methods are available to prevent redundant types in Typescript?

Consider an enum scenario: enum AlertAction { RESET = "RESET", RESEND = "RESEND", EXPIRE = "EXPIRE", } We aim to generate various actions, illustrated below: type Action<T> = { type: T; payload: string; }; ty ...

Troubleshooting: Imported Variable in Angular 2+ Throwing Module Not Found Error

During my testing process, I encountered an issue when trying to require a .json file with data to perform checks on. Despite passing the string indicating where to find the file into the require function, it seems to be unsuccessful... Success: const da ...

Incorporating a unique variant with Tailwind called "

I'm currently struggling with inputting the configuration file for Tailwind. Despite my efforts, I cannot seem to get it right. The code appears correct to me, but I am unsure of what mistake I might be making. Below is the snippet of my code: import ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Declaring properties for an interface

I've recently started using Typescript and I'm facing a problem with some interface props. There is an error message that says "Property 'services' does not exist on type 'IntrinsicAttributes & AkkordionProps[]", I'm confu ...

Manipulate the 'i' variable within a for loop using JavaScript, JQuery, and JSON to modify an attribute

I have 4 picture locations saved in a JSON file named img0, img1, img2, and img3. By using an AJAX call (getJSON), I retrieve the data from the file and then assign them to the "src" attribute of the images on my webpage. Everything works fine with this c ...