Introduction
In this lab, we will be exploring the concept of JavaScript programming and its various features and functionalities. Through practical exercises and hands-on programming assignments, we will delve into the core concepts of JavaScript such as functions, arrays, objects, and more. By the end of this lab, you will have a solid understanding of JavaScript and its practical applications in web development.
How to Calculate the Median of an Array of Numbers
To calculate the median of an array of numbers, follow these steps:
- Find the middle of the array.
- Use
Array.prototype.sort()to sort the values. - If
Array.prototype.lengthis odd, return the number at the midpoint. If it is even, return the average of the two middle numbers. - To start practicing coding and using
node, open the Terminal/SSH and typenode.
Here's an example code snippet that implements this logic:
const median = (arr) => {
const mid = Math.floor(arr.length / 2),
nums = [...arr].sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
You can call this function with an array of numbers as shown below:
median([5, 6, 50, 1, -5]); // 5
Summary
Congratulations! You have completed the Median lab. You can practice more labs in LabEx to improve your skills.