Generating a variety of modes from an array

My challenge is finding multiple modes from an array, but my code currently prints the modes multiple times. I specifically want to create an array with only 7 and 8 like this [7, 8] instead of [7, 7, 7, 7, 7, 8, 8, 8, 8, 8]. Can someone please assist me in fixing this issue?

const array = [1, 1, 2, 2, 2, 5, 5, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9];
let maxStreak = 0; 
let modus = [];

for (let i = 0; i < array.length; i++) {
  var series = 0;
  for (let j = 0; j < array.length; j++) {
    if (array[i] == array[j]) {
      ++series;
    }
  }
  
  if (series > maxStreak) {
    maxStreak = series;
    modus = [];
    modus.push(array[i]);
  } else if (series == maxStreak) {
    modus.push(array[i]);
    console.log(modus);
  }
}

I attempted a solution but still need it to output only 7 and 8 once.

Answer №1

Issue: The issue with your code is that you are logging the value in each iteration of the loop instead of waiting for the final result stored in the modus variable.

Resolution: To fix this problem, make sure to move the console.log statement outside of the loop as demonstrated in the sandbox solution provided below.

const array = [1, 1, 2, 2, 2, 5, 5, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9];
let maxStreak = 0; 
let modus = [];

for(let i = 0; i < array.length; i++){
    let series = 0;
    for(let j = i + 1; j < array.length; j++){
        if(array[i] === array[j]){
          ++series;
        }
    }
    if (series > maxStreak){
        maxStreak = series;
        modus=[];
        modus.push(array[i]);
    }else if(series == maxStreak){
        modus.push(array[i]);
    }
}

console.log(modus)

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

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Having difficulty sending file input contents to controller action with jquery in ASP.Net Core 6.0

When attempting to send a file to a controller action for saving, I encountered two issues. The first problem arose when using $.post to submit the data: $("#setting-form").on("submit", function(event) { var formData = new FormData(); ...

Smooth scrolling problems arise when a page loads and the offset jumps unexpectedly when the ID and hash are set to the same value

UPDATE: I'm considering converting this to jQuery, similar to the example here: http://davidwalsh.name/mootools-onload-smoothscroll Situation: Working on a Wordpress site with subnav navigation set for smooth scrolling down the page using /page/#idna ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

How can you handle events on DOM elements that haven't been created yet in JavaScript?

In my JavaScript module, I have the following code: EntryController = function$entry(args) { MainView(); $('#target').click(function() { alert('Handler called!'); }); } The MainView() function includes a callback ...

Help with guiding and redirecting links

Here's the code snippet: <script> if(document.location.href.indexOf('https://thedomain.com/collections/all?sort_by=best-selling') > -1) { document.location.href = 'https://thedomain.com/pages/bestsellers'; } </script& ...

Best practices for refreshing the HTML5 offline application cache

My website utilizes offline caching, and I have set up the following event handler to manage updates: applicationCache.addEventListener('updateready', function () { if (window.applicationCache.status == window.applicationCach ...

Error message: Uncaught TypeError - Unable to retrieve data using POST method in react with node and express servers

I am currently working on creating a Login / Register form using react for the client-side and node / express / (mongo) for the backend. The backend functionality is working smoothly as expected, with successful storage of credentials in the database upon ...

Is it possible to retrieve data from a particular index within an array using Mongoose

For instance, if the following is my documents: { "field": [ "hello", "random wording", { "otherId": 3232, "otherId2": 32332 } ], } Would it be possible to create a query that matches both i ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...

All about the ins and outs of JavaScript and manipulating the

I attempted to use DOM manipulation to change the page background color and div background color by utilizing getElementById and onclick methods. I wrote some code to make this happen, but unfortunately, it did not work as expected. Can anyone identify wh ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

What is the best way to retrieve a complete DynamoDB scan response using aws-sdk-js-v3 without object types included in the marshaled response?

After struggling with the AWS JS SDK V3 documentation and examples, I decided to share my findings to help others. The official SDK docs were frustrating and misleading, especially when it came to showing marshaled output properly. While the DDB Doc client ...

updating the v-model in Vue.js datepicker retains the previously set value while setting a new date

When using the template, the endDate updates as expected. However, there seems to be an issue when the filtersChanged method is called with the @selected attribute - the updated value is not the new one but rather the previously set value. <template&g ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

A guide on displaying JSON response data in Angular JS with the help of ng-repeat

I am attempting to display the values of a specific JSON in the correct order. Here is how my JSON is structured : { "A":[{"id":"21","name":"Andrea"},{"id":"22","name":"Apple"}], "B":[{"id":"21","name":"Baby"},{"id":"22","name":"Bali"}], "C":[{"id":"21"," ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

Retrieve information from a text

I retrieved this data as a string from a webpage using jQuery and need help parsing it. When I attempted to use jQuery.parseJSON, I encountered the error Uncaught SyntaxError: Unexpected token n. The specific values I am looking for are "surl" and "imgur ...

Preventing Event Bubbling with Hammer.js 2.0: A Step-by-Step Guide

I have a situation with a parent and child div. I want to prevent panning or dragging on the child from affecting the parent. I came across a similar question that was asked a year ago, but I am using a newer version of Hammer.js with the jQuery wrapper. ...