find the median of a list of numbers in javascript
To find the median of a list of numbers in JavaScript, we can follow these steps:
Sort the list of numbers in ascending order.
Check if the length of the list of numbers is odd or even.
If the length of the list is odd, return the number in the middle of the list.
If the length of the list is even, return the average of the two numbers in the middle of the list.
Here's the JavaScript code to implement this algorithm:
index.tsx
functionmedian(numbers) {
// sort the numbers in ascending order numbers.sort(function(a, b) {
return a - b;
});
// get the middle indexvar middle = Math.floor(numbers.length / 2);
// check if the length of the list is odd or evenif (numbers.length % 2 == 0) {
// return the average of the two numbers in the middle of the listreturn (numbers[middle - 1] + numbers[middle]) / 2;
} else {
// return the number in the middle of the listreturn numbers[middle];
}
}
// example usagevar list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
var result = median(list);
console.log(result); // output: 4