Calculate the mean value of each array, and then determine which average is higher

After running the code snippet provided, I noticed that it outputs "first" instead of "second". Can you help me verify my logic here? I first calculate both averages and then compare them to return the greater one. Do you see any issues with this approach?

var first = ([100, 80], [100, 100]);
function compare(a, b) {
  sum = 0;
  for(var i = 0; i < a.length; i++) {
    sum += first[i];
    avg1 = (sum/a.length);
  }

  sum2 = 0;
  for(i = 0; i < b.length; i++) {
    sum2 += first[i];
    avg2 = (sum2/b.length);
  }
  if (avg1 > avg2); {
    return ("first");
  }
  if (false) {
    return ("second");
  }
}

Answer №1

To calculate the average of the elements in arrays a and b, make sure you are summing those elements individually, not from array first.

Moreover, there was a redundant ; after if (avg1 > avg2), which resulted in an empty body for that condition. This caused return "first" to be executed unconditionally.

function compare(a,b) {
    var sum = 0;
    for(var i=0; i<a.length;i++) {
        sum += a[i];
        var avg1 = (sum/a.length);
    }

    var sum2 = 0;
    for(i=0;i<b.length;i++) {
        sum2 += b[i];
        var avg2 = (sum2/b.length);
    }
    if (avg1 > avg2) {
        return "first";
    } else {
        return "second";
    }
}
alert(compare([80, 100], [100, 100]));
alert(compare([100, 150, 200], [50, 75, 100, 110]));

Answer №2

If you're looking for a simpler method...

Check out my response to a similar query on calculating the average of an array using JavaScript.

var avg = myArray.reduce(function(a, b) {
    return a + b;
}) / myArray.length;

You can apply this to both arrays and utilize Math.max() to identify the higher average between them. The combined function would appear as follows:

var highestAvg = function (arr1, arr2) {
    return Math.max( arr1.reduce(function(a, b) {
        return a + b;
    }) / arr1.length, arr2.reduce(function(a, b) {
        return a + b;
    }) / arr2.length );
}

If you prefer to display the original array or terms like "first", then you simply compare the averages:

var greaterAverage = function (arr1, arr2) {
    var avg1 = arr1.reduce(function(a, b) {
        return a + b;
    }) / arr1.length;

    var avg2 = arr2.reduce(function(a, b) {
        return a + b;
    }) / arr2.length;

    if (avg1 < avg2) {
        return avg1; // or return "first";
    } else if (avg1 > avg2) {
        return avg2; // or return "second";
    }
}

Answer №3

A more straightforward approach is to clearly define the concept of average.

The average of a set of numbers is calculated by adding all the numbers together and then dividing by the total count of numbers in the set. I have chosen to let an error occur when trying to find the average of an empty set as mathematically, it doesn't make sense. However, some may prefer to handle this situation by returning zero instead.

To calculate the sum of the numbers, you can use the reduce method on the array by adding each element together.

var First  = [1,2,3],
    Second = [3,4,5];

function avg(A) {
    var Total = A.reduce( function(L,R) { return L+R; } );
    return Total / A.length;
}

window.alert( (avg(First) > avg(Second))? 'First' : 'Second' );

Answer №4

Initially, there was a mistake in your syntax for the if else statement. The correct syntax for the if else statement should look like this:

if (condition) {
    // block of code to be executed if the condition is true
} else { 
    // block of code to be executed if the condition is false
}

For example,

If the time is before 20:00, display a "Good day" greeting; otherwise, show "Good evening":

if (time < 20) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}

The output will be: Good day.

You can view the corrected code on this jsfiddle link here: Corrected code

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

Unable to make changes to the text within the textarea field

Currently, I am in the process of creating a script to streamline the tedious task of providing teaching feedback. To scrape data such as student names and classes, I am utilizing selenium/python. While everything is running smoothly, I have encountered an ...

I have my doubts about whether I am implementing the recapcha API correctly in a React application

I implemented the recapcha API in order to prevent bots from submitting posts on a forum site. As a new developer, I'm not sure if this is a real threat or not, as the users are limited to a maximum of 3 posts before they have to pay for more. I' ...

Interacting with various cookies created from user-provided input (specifically from textboxes) simultaneously

I'm facing a challenging problem and I'm in need of some assistance. The task at hand is to create three text boxes for users to input values for cookies named: name, city, and hobby. Then, using a single button with an onclick event, a function ...

Using an outdated version of Node.js to set up a React App

Attempting to utilize Create React App but encountering an issue that demands Node 10 or above. Presently, my node version is Node 8.10.0 and unfortunately, I am unable to update the Node version as it's a work device. Is there a method to operate an ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Information is not appearing in the dropdown menu

As a beginner in JavaScript, this is my first program. I have written HTML and JavaScript code to display data in a dropdown menu from a Python Django database. However, when I run it, the data is not showing up. Here is my code: <!DOCTYPE html> < ...

What's the best way to format text as bold in a .ts file so that it appears as [innerText] in the HTML section?

When looking to emphasize specific text without using [innerHTML], what is the alternative method besides the usual line break changes in the interface? How can we make certain text bold? For instance: .ts file string = This is a STRING bold testing.&bso ...

Having difficulty making changes to specific category fields in Magento 1.6

I've encountered an issue when trying to save specific fields in certain categories while editing them in Magento 1.6. The problem arises when attempting to edit the following fields within these categories: america/mini packages - description ameri ...

When hovering over a select option, a description and clickable link will be displayed

I need to display a description with a clickable link when hovering over any option in the select tag. <div class="col-lg-4"> <div class="form-group"> <label class="form-label">Goal</label> <select name="semiTaskType ...

Is it possible to change the return value of an Object key to something other than a string in REACT? Issue with RE

In an attempt to modify the data in an object using the setState method in 'react', I decided to take a different approach. Instead of creating a function for each key in the state object, I attempted to create one object and return the key from ...

Tips for altering the appearance of the material-ui slider thumb design when it is in a disabled state

Through the use of withStyles, I have successfully customized the style of the Slider: const CustomSlider = withStyles(theme => ({ disabled: { color: theme.palette.primary.main }, thumb: { height: 24, width: 24, }, }))(Slider); How ...

Using jQuery UI to create sortable lists that are connected and have hidden overflow features

How can I hide overflow from two fixed-height divs containing sortable lists connected to each other without affecting their connection? For example, if overflow is set to hidden, the list item doesn't display when dragged outside of the div. I' ...

Prioritize loading CMS content before mounting the React component

I am facing a challenge with importing my post from ButterCMS to React due to the async issue. import React, { useState } from "react" import Butter from "buttercms" import gradient from "../../images/TealLove.jpg" export default () => { const butt ...

The combination of React.js and debouncing on the onChange event seems to be malfunctioning

I recently incorporated a React component that triggers an event on change. Here's how I did it: NewItem = React.createClass({ componentWillMount: function() { this._searchBoxHandler = debounce(this._searchBoxHandler, 500); }, _searchBoxH ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

Bootstrap 5 alert: The function `$(...).carousel` is not recognized

Despite browsing through numerous similar questions, none of the solutions seem to work for my issue. Listed below are some points I have checked: Jquery is loaded before bootstrap Bootstrap libraries are up to date Confirmation that bootstrap.min. ...

Encountering a parsing issue: an unexpected token was found, expecting "," instead

I'm encountering a Parsing error that states: Unexpected token, expected ",". I've been unable to pinpoint where the missing "," is located. Please refer to the image below for the exact line of the error. const cartSlice = createSlice({ name ...

Modifying the URL does not alter the selected tab

As part of my project, I wanted to ensure that when the page is refreshed, the previously selected tab remains active. To achieve this, I created a basic HTML page and added some jQuery. However, I encountered an issue when manually changing the URL from ...

Encountering issues when using array.map with null entries in a react application

Struggling to iterate over the location array and map it? Despite several attempts, handling the null object within the array seems challenging. What am I missing here? While using a for loop resolves the issue, the map function is proving to be a roadbloc ...