How to Remove Smallest and Largest Elements from an Array in JavaScript ?
Last Updated :
12 Jul, 2024
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:
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using the reduce() Method
Here, this approach uses the reduce() method in JavaScript where we will iterate through the inputted array and find the largest and smallest element. Then we will maintain a result array in which we will append or store only the elements that do not match the largest and smallest element conditions specified in the if condition.
Example: In this example, we are using reduce() method in JavaScript.
JavaScript
// Using reduce() method
let inputArray = [3, 1, 7, 9, 2, 8, 4, 6, 5];
let smallestElement = Math.min(...inputArray);
let largestElement = Math.max(...inputArray);
inputArray =
inputArray.reduce((newArray, currentElement) => {
if (currentElement !== smallestElement &&
currentElement !== largestElement) {
newArray.push(currentElement);
}
return newArray;
}, [])
console.log(inputArray);
Output[
3, 7, 2, 8,
4, 6, 5
]
Here, in this approach, we will use the for loop for removing the smallest and largest element from the given array. We will compare each element with the min and max elements and we will store the newly created array in another array variable.
Syntax:
for (let i = 0; i < inputArray.length; i++) {
// Code..
}
Example: In this example, we are using the iteration loop (for) in JavaScript
JavaScript
//Using For loop
let inputArray = [10, 45, 78, 23, 44, 11, 67];
let smallestElement = Math.min(...inputArray);
let largestElement = Math.max(...inputArray);
let newArray = [];
for (let i = 0; i < inputArray.length; i++) {
if (inputArray[i] !== smallestElement &&
inputArray[i] !== largestElement) {
newArray.push(inputArray[i]);
}
}
console.log(newArray);
Output[ 45, 23, 44, 11, 67 ]
Here, in this approach, we create a new array by using the filter() function in JavaScript which actually excludes the smallest and largest elements and results in the removal of these values from the original inputted array in the code itself.
Syntax:
for (let item of inputArray) {
// Code . . .
}
let newArray = inputArray.filter();
Example: In this example, we are using the above-explained approach.
JavaScript
// Without using Math.min() and Math.max()
let inputArray = [10, 5, 4, 6, 8, 1, 3, 9, 2];
let smallestElement = Infinity;
let largestElement = -Infinity;
for (let item of inputArray) {
if (item < smallestElement) smallestElement = item;
if (item > largestElement) largestElement = item;
}
let newArray =
inputArray.filter(
num => num !== smallestElement && num !== largestElement);
console.log(newArray);
Output[
5, 4, 6, 8,
3, 9, 2
]
To remove the smallest and largest elements from an array, use array.sort() to sort in ascending order, then array.slice(1, -1) to remove the first and last elements.
Syntax:
function remove(arr) {
arr.sort((a, b) => a - b);
arr = arr.slice(1, arr.length - 1);
return arr;
}
Example: In this example, we are using the above-explained approach.
JavaScript
function remove(arr) {
arr.sort((a, b) => a - b);
arr = arr.slice(1, arr.length - 1);
return arr;
}
const newArray = [10, 5, 4, 6, 8, 1, 3, 9, 2];
const result = remove(newArray);
console.log(result);
Output[
2, 3, 4, 5,
6, 8, 9
]
Approach 5: Using Array.splice() and Array.includes()
Using `Array.splice()` with `Array.includes()`, the function repeatedly removes the smallest and largest elements from the array until neither is present. This approach directly manipulates the array based on element inclusion checks.
Example
JavaScript
function removeMinMax(arr) {
let min = Math.min(...arr);
let max = Math.max(...arr);
while (arr.includes(min) || arr.includes(max)) {
arr.splice(arr.indexOf(min), 1);
arr.splice(arr.indexOf(max), 1);
}
return arr;
}
let array = [1, 5, 3, 7, 2, 9];
removeMinMax(array);
console.log(array); // [5, 3, 7, 2]
Method 6: Using Array.filter() and Math.min/Math.max()
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.
JavaScript
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]
Approach 7: Using a Set to Remove Elements
In this approach, we will use a Set to remove the smallest and largest elements from the array. We first identify the smallest and largest elements and then use the Set object to store only the elements that are not the smallest or largest. Finally, we convert the Set back to an array.
Example: Using a Set to Remove Elements
JavaScript
// Using Set
let inputArray = [4, 7, 2, 9, 1, 8, 3, 6, 5];
let smallestElement = Math.min(...inputArray);
let largestElement = Math.max(...inputArray);
let resultSet = new Set(inputArray);
resultSet.delete(smallestElement);
resultSet.delete(largestElement);
let resultArray = Array.from(resultSet);
console.log(resultArray);
Output[
4, 7, 2, 8,
3, 6, 5
]
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read