Using Javascript to create an array filled with even numbers up to 100 and then calculating the average

Hey there, I'm struggling with a class assignment that involves finding the average of an array of even numbers that we're supposed to generate. Unfortunately, I can't seem to get it working properly.

var arrayOfNumbers = [];
for (var num = 1; num <= 100; num++) {
  if (num % 2 == 0) {
    arrayOfNumbers.push(num);
  }
}
var sum = 0;

for (var index in arrayOfNumbers) {
  sum += arrayOfNumbers[index];
  sum / 50;
}

document.write(sum);

I've included the code above - could you please point out what I might be doing wrong? It seems like the array isn't populating with even numbers as expected. Any assistance would be greatly appreciated since my professor doesn't respond to emails quickly.

Thank you!

Answer №1

There is an alternative way to solve this without using an array:

sum = 0;
count = 0;
for (var num = 1; num <= 100; num++) {
    if(num % 2 == 0) {
        sum += num;
        count++;
    }
}
document.write(sum/count);

However, if you prefer to use an array:

var newArray = [];
for (var num = 1; num <= 100; num++) {
    if(num % 2 == 0) {
        newArray.push(num);
    }
}
var newTotal = 0;
for(var index in newArray) { 
  newTotal += newArray[index]; 
}
document.write(newTotal/newArray.length);

Answer №2

To get the sum of all elements and calculate the average, you can utilize a reducer function. Remember to use == instead of i % 2 = 0. See the example implementation below.

let numberArray = [];

// populate array
for (let i = 1; i <= 100; i++) {
  if (i % 2 == 0) {
    numberArray.push(i);
  }
}

// compute total
const totalSum = numberArray.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

// find average
const averageValue = totalSum / numberArray.length;

document.write(averageValue);

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

Building a Fullscreen Modal with Bootstrap in React is a great way to

Utilizing the Modal component from bootstrap for React, as seen here. To create a Modal, the following code is used: import React, {Component} from 'react'; import {BaseComponent} from 'BaseComponent'; import { Modal, Button } from &ap ...

Encountered issue in mounted hook: "TypeError: Unable to access 'dispatch' property of undefined"

I need help writing a test for my Vue component. The component makes an async call on mount and updates the Vuex store, but this causes issues with my current unit tests because 'dispatch' is called during mount. Does anyone have any suggestions ...

String array pointer

I'm having trouble with a section of my code: char *arrStr[3]; arrStr[0] = "hello"; //this line works *(arrStr+1) = "world"; //this line works too arrStr++; // why doesn't this work? char **arrStr2 = arrStr; //this works arrStr ...

Having trouble with the authorization aspect of Next Auth. The error message reads: "NextAuth.js does not support the action api with HTTP GET method

Recently, I've been encountering a puzzling error with my Next.js app authentication. It seems that I am unable to authenticate with the provided credentials. After reviewing the documentation, everything appears to be correct on my end. Additionall ...

Execute a client-side Javascript query through Express (node.js) framework

As I work on developing a web application with Express, I encounter the need for users to modify data within a table on one of the pages. To enable this functionality, I implement the use of contenteditable in HTML5 (you can see a DEMO here: http://jsfiddl ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

React eliminates all white spaces

Presented here is a compilation of various span elements: <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> Accompanied by the CSS style for these elements: span{ bac ...

Error in TypeScript: Cannot declare block-scoped variable 'fetch' more than once

Currently, I am in the process of creating a proof of concept where I need to fetch some basic JSON data from JSON-server for display in my react app. While attempting to directly call fetch to retrieve the data, I encountered the following error message: ...

How can we determine the number of duplicate elements in an array?

Is there a way to tally the occurrences of specific words from a list within a given set of phrases and store the count in designated variables? let counter = []; let wordToCount = ["tomato","cat"]; let phrasesToCheck = ['my cat like potatoes', ...

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...

Executing JavaScript code in the Selenium IDE

I'm having trouble figuring out how to execute JavaScript within the Selenium IDE. The objective is to enter text into an input field, with a backend setup that verifies the current time in the input field for testing purposes: Here's the input f ...

What could be causing the Or operator to malfunction within the ng-pattern attribute in AngularJS?

Currently, I am implementing the ng-pattern="/^(([A-Za-z]{0,5}) | ([0-9]{0,10}))$/". However, it seems like the input control is not accepting values such as "asd" or "09", despite my expectation that both should be valid inputs. Do you think the pipe sy ...

Get the array from the input field

Could you please take a look at this function I have written: function AddRowToForm(row){ $("#orderedProductsTblBody tr").each(function(){ // find the first td in the row arr.push($(this).find("td:first").text()); }); for (i=0;i<arr.length ...

AngularJS bypass routing with ui-router

I am attempting to switch from the built-in Angular route mechanism to ui.router. To do this, I have included angular.ui.router.js in my index.html and in my module: var app = angular.module('multibookWeb', ['ui.router']); After that, ...

Which would be more advantageous: using a single setter method or multiple setter methods for objects that have a set number of fields?

As I ponder over designing a class with a member variable of type object containing a fixed number of fields, the question arises: should I opt for a single setter function or multiple setters to modify these fields? To illustrate this dilemma clearly, I ...

Enhance the appearance of unordered lists within list items using Vue.js for added style

I'm currently encountering an issue on how to apply styling to a ul element inside a clicked li using Vue JavaScript. Here is my HTML code: <ul> <li>Menu</li> <li @click="toggleSubMenu">Profile <ul> ...

Using an Ajax call to show a date picker when a button is clicked

I've created buttons for each ID in the "habitaciones" table. When a button is clicked, it should display a specific datepicker with dates disabled for that ID. To achieve this, I utilized an Ajax function where the form should be displayed based on ...

The issue arises with the Google Map marker failing to function correctly when pulling data

I've recently started learning Google Maps. It's interesting that markers work and are displayed when statically declared, but not when retrieved from a database. // var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.69 ...

JavaScript's ASYNC forEach function not following the expected sequence

I'm really struggling to understand the workings of async and await in this scenario. I want the forEach function to run before the console.log and res.json, but no matter what I do with async and await, it always ends up being the last thing executed ...

Encountering the "Error: JSON.parse: unexpected character" when trying to retrieve JSON data using AngularJS

I've been struggling with this issue for the past few days. Every time I attempt to fetch a JSON object using Angular's $http.get method, I encounter the error message "Error: JSON.parse: unexpected character". The JSON data is generated using P ...