Table of Contents
Problem Statement
Example
algorithm
in conclusion
Home Web Front-end JS Tutorial JavaScript program to find range average in array

JavaScript program to find range average in array

Sep 15, 2023 am 11:09 AM

JavaScript 程序求数组中的范围平均值

Given an array of numbers and a range, the goal is to calculate the average of all numbers in the range. This problem can be solved in many ways, but in this tutorial we will explore a simple yet effective solution using JavaScript. We'll first define the problem in more detail, including an example of how the function should work. We'll then break down the solution step-by-step, with clear explanations and code snippets. By the end of this tutorial, you will have an in-depth understanding of how to write a JavaScript program that calculates the average of a range in an array. So let’s get started!

Before we begin, let’s define what “average” means. In mathematics, the average (also called the mean) is calculated by adding all the values ​​in a set of numbers and then dividing the sum by the number of values. In the context of an array, the mean of a range of values ​​is the average of all values ​​in the range.

Problem Statement

Given an array of numbers and a range of two numbers, the goal is to calculate the average of all numbers in the range. The range is inclusive, meaning it should include the first and last number in the range. The function should take as input an array and a range and output the average of the numbers in the range. If the input array is empty, the function should return null. The function should also return null if the range is invalid (i.e. the first number is greater than the second number). The output should be a floating point number with two decimal places.

Let us understand this with some examples -

Example 1

Input: Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   Range: [3, 7]
Output: Mean of range [3, 4, 5, 6, 7] is 5.00
Copy after login

In example 1, we have an array of numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and a range [3, 7]. The average of the range [3, 4, 5, 6, 7] is 5.00, so the output should be 5.00.

Example 2

Input: Array: [2, 4, 6, 8, 10, 12]
   Range: [1, 5]
Output: Mean of range [2, 4, 6, 8, 10] is 6.00
Copy after login

In example 2, we have an array of numbers [2, 4, 6, 8, 10, 12] and the range [1, 5]. The average of the range [2, 4, 6, 8, 10] is 6.00, so the output should be 6.00.

Example 3

Input: Array: [3, 5, 7, 9, 11, 13]
   Range: [7, 3]
Output: null
Copy after login

In example 3, the range [7, 3] is invalid because the first number is greater than the second number, so the output should be null.

Example 4

Input: Array: []
   Range: [1, 5]
Output: null
Copy after login

In example 4, the input array is empty, so the output should also be empty.

Now let us understand the algorithm for the above problem statement.

algorithm

Step 1 - Define function "meanInRange" which takes two parameters: array "arr" and range "range".

Step 2 - Check if the length of the input array "arr" is zero. If so, returns null.

Step 3 - Destructure the "range" array range into two variables "start" and "end".

Step 4 - Check if the value of "start" is greater than "end". If so, returns null.

Step 5 - Use the "slice" method to extract a subarray from the input array "arr" that contains only elements between the start index and the end index of the given range.

Step 6 - Calculate the sum of all elements in the subarray using the "reduce" method.

Step 7 - Divide the sum by the length of the subarray to get the average.

Step 8 - Returns the average as a string formatted to two decimal places, along with a message indicating the range of values ​​used to calculate the average.

Step 9 - End the function.

Now let us understand this algorithm through an example of implementing it using JavaScript.

Example

In this implementation, we define a function "meanInRange" that accepts the array "arr" and the range "range" as input. The function first checks if the input array is empty or if the range is invalid, and returns null if either condition is true. Otherwise, it slices the input array to get the range, uses "reduce" to calculate the sum of the numbers in the range, and calculates the average. Finally, the function logs the average, rounded to two decimal places, to the console using "console.log".

We then call the "meanInRange" function with different input arrays and ranges to test its functionality and print the output to the console.

function meanInRange(arr, range) {
   if (arr.length === 0) {
      return null; // return null if the input array is empty
   }
   const [start, end] = range;
   if (start > end) {
      return null; // return null if the range is invalid
   }
   const rangeArr = arr.slice(start - 1, end); // slice the array to get the range
   const sum = rangeArr.reduce((acc, num) => acc + num, 0); // calculate the sum
   const mean = sum / rangeArr.length; // calculate the mean
   // return the mean rounded to two decimal places
   return `Mean of range [${rangeArr}] is ${mean.toFixed(2)}`;
}
// Example usage:
console.log(meanInRange([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 7])); // should output "Mean of range [3,4,5,6,7] is 5.00"
console.log(meanInRange([2, 4, 6, 8, 10, 12], [1, 5])); // should output "Mean of range [2,4,6,8,10] is 6.00"
console.log(meanInRange([3, 5, 7, 9, 11, 13], [7, 3])); // should output "null"
console.log(meanInRange([], [1, 5])); // should output "null"
Copy after login

in conclusion

In this tutorial, we explored how to find the average of a series of values ​​in an array using JavaScript. We discuss the problem statement and provide algorithms and JavaScript programs that solve the problem. We also learned several usage examples and how to handle edge cases such as empty arrays or invalid ranges. By following this approach, you can easily calculate the average of a series of values ​​within an array in a JavaScript program.

The above is the detailed content of JavaScript program to find range average in array. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles