search
HomeWeb Front-endJS TutorialJavaScript program to find range average in array

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

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

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

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

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"

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools