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

The view has no access to $scope but the controller does

I need to display the iso code using a $scope when selecting a country from a list. The list of countries is fetched through a $http call in a factory and then stored in a scope. ///////// get countries //////////////// tableFactory.getCountries().then(f ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

Stop any accidental double clicks on the <input type="submit" /> to avoid duplicate entries

Is it possible to prevent a user from clicking twice on an input tag button with type submit? I attempted using ondblclick="javascript:void(0)", but it did not work. My code is within an Html.BeginForm, not a form element tag. Thank you in advance for al ...

Passing data from a Vue.js component to a router in index.js

I am attempting to transmit a JWT token value from the component Login.vue and verify it in the router/index.js before directing the user to the next page. Login.vue: <script> import axios from "axios"; export default { name: "Login", m ...

Troubles with the compatibility of javascript and jquery's multiselect plugin

I've been utilizing the multiselect API to create a dropdown with multiple select options. This is my HTML code: <select id="options" multiple="multiple"></select> And this is my JS code: render:function(){ // $('#viewTemp& ...

There is a lack of 'Access-Control-Allow-Origin' header, resulting in no access to the API

Having some trouble with the UK Parliament API, I keep encountering this error: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not a ...

Change button to an ajax spinner when it is clicked using jQuery

$(".post-btn").html("<img src='../images/loader.gif' />"); Why isn't this code working? I know I have the correct selector because when I tried $(".post-btn").text('test'), it worked. I want the text of the button to change ...

Check if a Discord.js bot responds based on whether a user holds a designated role

I'm looking to make my bot respond to a specific role. If the user does not have that role, I want the bot to reply with a message saying "You are not allowed to perform this command." Here is the code snippet I am using: client.on("message", (message ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

Creating an object and setting its prototype afterwards

While exploring examples and questions online about prototypal inheritance, I noticed that most of them involve assigning prototypes to constructor functions. One common pattern is shown in the code snippet below: Object.beget = function (o) { var F = ...

Enhance a path SVG component with properties for a map in a React application

My goal is to develop a strategy game using an SVG map that I have created. I want to include attributes such as "troops" in each "path" representing territories, along with other properties. Can I add these attributes to individual paths and then use this ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

"An unexpected compilation error (800A03EA) has occurred in the JavaScript syntax during

My computer is facing a frustrating compilation issue with JScript and node. Despite trying various solutions found online, the problem persists. After navigating to CD>PROJECT: npm init successful npm install -g globally and locally installed correct ...

Guide to dynamically updating a textarea in vue.js by incorporating data from several inputs

Is there a way to update a textarea based on multiple inputs using jQuery and vue.js? I have successfully implemented the jQuery part with line breaks, but when I try to display the value of the textarea elsewhere using vue.js, it doesn't seem to work ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

A tool designed to create a function that can fetch information from a JSON file

Currently, I am working on a function that accepts arguments and combines them to form a line for searching data in a JSON file. To accomplish this, I have initialized a variable for the readFileSync and then added the function's arguments to it in or ...

The "body" object cannot be accessed in a post request made from an Express router

I am currently utilizing Express router functions to manage some POST requests. Client.js let data = { endpoint: "Blah Blah"; }; return fetch('/api/get-preferences/', { method: 'POST', headers: { 'Content-Type': & ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...