In the simple javascript program, we will understand how to Find the median of array elements in JavaScript in ES6
ES6 JavaScript Program to find the median of array elements
In this javascript program, we are using the spread operator to pass array element as an argument [. . .myarr]
const findmedian = myarr => {
const median = Math.floor(myarr.length / 2),
nums = [...myarr].sort((x, y) => x - y);
return myarr.length % 2 !== 0 ? nums[median] : (nums[median - 1] + nums[median]) / 2;
};
console.log('median of array is :',findmedian([3, 6, 9, 12, 15]));
Output
median of array is : 9