How to useArray.filter() and Math.min/Math.max() in Javascript
This approach combines the use of the Array.filter() method with Math.min/Math.max() to remove the smallest and largest elements from the array.
function removeMinMax(arr) {
// Find the minimum and maximum values in the array
let min = Math.min(...arr);
let max = Math.max(...arr);
// Filter out the elements that are equal to the minimum or maximum values
return arr.filter(num => num !== min && num !== max);
}
// Example usage
let array = [1, 5, 3, 7, 2, 9];
let result = removeMinMax(array);
console.log(result); // Output: [5, 3, 7, 2]
Output
[ 5, 3, 7, 2 ]
How to Remove Smallest and Largest Elements from an Array in JavaScript ?
We will cover how to remove the smallest and largest elements from an array in JavaScript. Removing the smallest and largest elements from an array in JavaScript means filtering out the minimum and maximum values from the original array, leaving only the intermediate elements. We will see the code for each approach along with the output.
There are several methods that can be used to remove the smallest and largest elements from an array in JavaScript, which are listed below:
Table of Content
- Using the reduce() Method
- Using the iteration loop (for)
- Using the Loop and filter() Method
- Using Array.sort() and Array.slice() Methods
- Using Array.splice() and Array.includes()
- Using Array.filter() and Math.min/Math.max()
We will explore all the above methods along with their basic implementation with the help of examples.