What is the solution for excluding 0s in my javascript code?

I am working on a code to calculate the average of four numbers entered by the user, but I want to exclude zeros from the calculation. Currently, the code successfully excludes one zero, but I am struggling to exclude multiple zeros. My initial approach was to remove any number containing a zero, so that the average is only calculated based on non-zero numbers. Here is the code snippet:

var num1 = parseInt(prompt("Enter the first number:"), 10);
var num2 = parseInt(prompt("Enter the second number:"), 10);
var num3 = parseInt(prompt("Enter the third number:"), 10);
var num4 = parseInt(prompt("Enter the fourth number:"), 10);
  
if (num1 == 0){
    document.getElementById("output").textContent = ((num2 + num3 + num4) / 3);  
}
if (num2 == 0){
    document.getElementById("output").textContent = ((num1 + num3 + num4) / 3);  
}
if (num3 == 0){
    document.getElementById("output").textContent = ((num1 + num2 + num4) / 3);  
}
if (num4 == 0){
    document.getElementById("output").textContent = ((num1 + num2 + num3) / 3);  
}
else {
    document.getElementById("output").textContent = ((num1 + num2 + num3 + num4) / 4);  
}

Answer №1

Ponder over your current train of thought.

You devised a code snippet that calculates the average of three numbers if one of the four numbers is zero. However, you've now realized that it fails to work when two of the four numbers are zeroes. How many additional if-else statements would you need to add to account for this scenario? Now, envision a situation where three of the numbers are zeroes.

This issue seems straightforward as it involves only four inputs. But imagine extending this to 100 inputs, aiming to calculate the averages of all non-zero integers from the inputs.

A more scalable solution would be to create a code that focuses solely on and averages the non-zero integers, regardless of the number of inputs. Consider the following approach:

let num1 = 3; //assumed to be equivalent to var num1 = parseInt(prompt("first number: "),10);
let num2 = 4; //assumed to be equivalent to var num2 = parseInt(prompt("second number: "),10);
let num3 = 0; //assumed to be equivalent to var num3 = parseInt(prompt("third number: "),10);
let num4 = 0; //assumed to be equivalent to var num4 = parseInt(prompt("fourth number: "),10);

const numbers = [num1, num2, num3, num4]

function avgNonZeroValues(nums){
  const nonZeros = nums.filter(number => number !== 0);
  const avgOfNonZeros = nonZeros.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  )/nonZeros.length;
  
  return avgOfNonZeros;
}

console.log(avgNonZeroValues(numbers));

It's important to familiarize yourself with two essential functions:

  1. reduce()

Reduce is a powerful method for iterating through a list/array and performing operations on it. By specifying an initial value (0 in our case) and the actions to be taken on each element, we can, in this scenario, obtain the sum of all numbers in the array.

  1. filter()

As the name suggests, the filter function takes an array and a condition, removes the elements that don't meet the criteria, and returns a new array with only the elements that satisfy the condition. In this case, we are using it to eliminate all zeros from the array.

Providing an array of any length containing numbers to the avgNonZeroValues function will result in the removal of all zeros before calculating the average of the remaining numbers.

Answer №2

When we refactor this code to utilize arrays, it becomes much easier to leverage array functions for filtering and transforming numbers.

const prompts = ["first", "second", "third", "fourth"];

const values = prompts
  .map(p => parseInt(prompt(`${p} number: `),10))
  .filter(v => v !== 0);

const total = values.reduce((acc, val) => acc + val, 0);
const avg = total/values.length;

console.log(total, avg);

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

Are you experiencing a clash among various JS files in your WordPress installation?

I'm in a bit of a bind here. I've been tasked with working on a Wordpress website for a friend, using a free theme that he provided. Naturally, he wants some modifications made, so I've been editing the theme accordingly. The theme relies on ...

Updating the checklist status using an ajax request: A step-by-step guide

Is it better to update the checklist status by making individual ajax calls for each checklist item or by making one call and updating it once completed? I have included a template showing how it currently looks and what I am aiming for. Unfortunately, I ...

Tips for navigating the HTML DOM without using window.scrollBy(x, y) (specifically for scrolling within an element)

Desiring to scroll down along with my selected document, I experimented with the following code. window.scrollTo(x, y); const body = document.getElementsByClassName("body")[0]; body.scrollTo(x, y); However, there are instances where it returns "undefined ...

One div takes a backseat to the other div

I recently delved into learning Bootstrap, but I'm baffled as to why one div is appearing behind another. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fa ...

Ajax call encounters 404 error but successfully executes upon manual page refresh (F5)

I am encountering a frustrating issue with my javascript portal-like application (built on JPolite) where modules are loaded using the $.ajax jquery call. However, the initial request fails with a 404 error when a user first opens their browser. The app i ...

Eliminate HTML TAG entries from the input form

My issue is that when I try to type a comma, it does not allow me to do so. How can I add other characters like <, >, /, \, etc? $("#in1").keypress(function (evt) { if (String.fromCharCode(evt.which) == ",") return false; }); < ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

Is there a way to extract a particular value from a JSON URL and transfer it to a JavaScript variable?

I am looking to extract current exchange rates from a JSON URL for implementation in a webpage. Specifically, I want to retrieve a particular exchange rate (such as the US Dollar) and store it in a variable for use within a JavaScript function. Below is a ...

Ways to determine the completion of the compilation process in Angular using the $compile service

Imagine having a popup directive that inherits a string template for the content it should display from the $scope. scope: { template: '=popInfo'//<div another directive></div> } This template string may even include another dire ...

Issue with PeerJs Localhost Setup

Implementing the zoom clone with WebRTC using peerjs, I am facing an issue where myPeer.on("call", (call) => { is not getting called. This code works fine for others on localhost who followed the tutorial on the zoom clone. I am unsure of what ...

Click to load an IFRAME upon clicking

I am encountering an issue with IFRAMEs loading onClick. The problem lies in the script provided below which always loads the content of the first iframe, whereas my expectation is to load only the iframe corresponding to the link clicked. $('.toggle ...

Automatically update and reload Express.js routes without the need to manually restart the server

I experimented with using express-livereload, but I found that it only reloaded view files. Do you think I should explore other tools, or is there a way to configure express-livereload to monitor my index.js file which hosts the server? I've come ac ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Tips for keeping the most recently opened accordion in a group by using the is-open attribute to call a function

I have a dynamically populated accordion that updates every 15 seconds. I need to keep track of the last opened accordion group as the dataList can be very large and parsing it for each update is not feasible. Below is the code snippet from my HTML file: ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

Create a Jest unit test for a specific function

I started my first unit test in react with jest this afternoon. The initial 5 tests I need to do involve testing the return functions, which isn't too difficult. However, I'm struggling to understand how to perform unit testing on my login funct ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

Tips for choosing elements that are not next to each other in a JavaScript array

If I have an array and want to select non-consecutive elements, such as the second and fifth elements, is there a simple method to do this? For example: a = ["a","b","c","d","e"] a.select_elements([1,4]) // should yield ["b","e"] EDIT: After some reflec ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Exploring the differences between client-side and server-side data manipulation

Recently, I discovered how to access local variables from Express in client-side JavaScript: Check out this helpful thread on StackOverflow However, this discovery has brought up a new challenge for me... Now I am unsure about which data manipulation tas ...