Debugging a script designed to output a value of 1 if the Mean equals the Mode, and 0 if they are not equal

As a beginner coder, I am working on a code that should return 1 if the mean is equal to the mode and 0 otherwise. However, my current code only outputs 0 even when it should be returning 1. Any guidance or assistance in identifying where I may have made an error would be highly appreciated!

function ArrayChallenge(arr) { 
let sum = 0;
let totalNum = arr.length;
let mean = sum / totalNum;
for (i = 0; i < arr.length; i++) {
  if (arr[i] > 0) {
    sum += arr[i];
  }
}

const numList = {};
arr.forEach(elem => numList[elem] = numList[elem] + 1 || 1);
let mode = [];
let numMax = 0;
for (const key in numList) {
  if(numList[key] > numMax) {
    mode = [Number(key)];
    numMax = numList[key];
  } else if (numList[key] === numMax) {
    mode.push(Number(key));
  }
}
if (mode.length === Object.keys(numList).length) mode = [];
if (mean === mode) {
  return 1;
} else return 0;
} 

Answer №1

To ensure that <code>sum is properly populated, it is essential to place the calculation of mean = sum/totalNum after the for loop.

for (i=0; i < arr.length; i++) {
    if (arr[i] > 0) {sum+= arr[i]}
}
let mean = sum/totalNum

When checking for either a return value of 1 or 0, there is a comparison error between mean (a number) and mode (an array). By incorporating mode.length, you can obtain the actual length (number) of the array for comparison.

if (mean === mode.length) {
  return 1
} else return 0
} 

RESULTS: Based on your code, the expected outcomes for the test data will be as follows:

//ArrayChallenge([10,10,10]) -> 0
//ArrayChallenge([0,0,0]) -> 1

Please note that these results assume that you intend to compare the length of the mode array. Providing additional context about the problem would be helpful for better understanding.

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 steps can I take to resolve a Bootstrap form validation issue where the email field is causing the label to shift down?

I am currently troubleshooting an issue in a website using Visual Studio, which is built with VB.NET, ASP.NET, HTML, CSS, and Bootstrap. The problem lies in the input validation under the email addresses. While one validation is working fine, the validatio ...

Acquire HTML table information in array format using JavaScript

I am searching for a script that can extract the 2D array of rows and columns from an HTML table within a div element. The desired array output should be: [ ["Company", "Contact", "Country"], ["Alfreds Futterkiste", "Maria Anders", "Germany"], ...

New approach: AngularJS - Using nested ng-click events

Looking for a solution to a problem with my html code: <div class="outerdiv" data-ng-click="resetText()"> <div class="innerdiv" data-ng-click="showText()"> {{ text }} </div> </div> The outer div has an ng-click fun ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Is there a way to convert a json array to a javascript array in AngularJs?

I am new to Angular and front-end development and facing a challenge that I can't seem to overcome. After reassigning one variable to another: $scope.testarray = $scope.todos; only the 'todos' data is being displayed when using Angular bind ...

Leverage predefined JavaScript functions within an Angular template

I have been attempting to execute an eval function within my angular template in the following manner: <div *ngFor="..."> <div *ngIf="eval('...')"></div> </div> You understand what I'm trying to ...

"Using a WMD Editor to show the content of the wmd-preview division and questions on how to save this content in a

I am currently in the process of integrating the WMD editor into my website. Everything seems to be functioning correctly so far, but I have hit a roadblock: How can I store the entered information in my database? I have developed a JS/Ajax function that a ...

Combine the promises from multiple Promise.all calls by chaining them together using the array returned from

I've embarked on creating my very own blogging platform using node. The code I currently have in place performs the following tasks: It scans through various folders to read `.md` files, where each folder corresponds to a top-level category. The dat ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

Changing images in vuejs

I am seeking to achieve a seamless transition between two images along with a corresponding legend. These images are sourced from an object-array collection. Since transitions operate only on single tags and components, I have devised a component to encap ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

Showcasing items from a JSON document

I am looking for guidance on how to map and access data. Specifically, I need help printing out a list of all the "url" links in the JSON file. Check out this example of the json structure return pressReleases ? ( <Main> {pressReleases.map((item) ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

Utilize puppeteer by passing a function inside page.waitForFunction() for efficient automation processes

Below is the code I am using: function checkDataRefresh(pastAvgGain, currentAvgGain) { if (pastAvgGain !== currentAvgGain) { return true; } else { return false; } } async function fetchInformation(pair, page) { let pastAvgGain = C.AVG ...

Conceal an element along with its space, then signal the application to show alternative content using React

Greetings everyone! I seek assistance with a React Application that I am currently developing. As a newcomer to the Javascript world, I apologize if my inquiry seems trivial. The application comprises of two main elements: a loader, implemented as a React ...

error is not defined in the onsuccess function of the ajax.beginform partial view

Currently, I am working on an MVC5 project where a View is calling a Partial View. Within the Partial View, there is an Ajax.BeginForm that triggers a function on OnSuccess. However, during execution, I encounter an error stating that the function cannot ...

Numerical values are not considered by the JavaScript table filter

I'm having trouble with dynamically filtering the content. It works fine for the first two columns, but not for the third one. Maybe I need some additional JavaScript? Here is the link to my snippet: `https://www.w3schools.com/code/tryit.asp?filen ...

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

Vue.JS is throwing a TypeError: Unable to employ the 'in' operator to look for 'undefined' within the Laravel Object

How can I successfully pass an object from Laravel to Vue.js and utilize it in a v-for="option in this.options"? Although I am able to transfer the object from my Laravel blade to the Vue.js component and view it in the console, I encounter an error when a ...

An error occurred stating 'TypeError: jsdom.jsdom is not a function' while using the paper-node.js in the npm paper module

Recently, I added the webppl-agents library to my project, including webppl and webppl-dp. However, when attempting to execute the command line test, I encountered some difficulties. It seems that there is a dependency problem with jsdom from the npm paper ...