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
JavaScript Program to Remove Duplicate Elements From a Sorted Array
Given a sorted array arr[] of size N, the task is to remove the duplicate elements from the array. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: arr[] = {2} Explanation: All the elements are 2, So only keep one instance of 2. Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output: arr[] = {1, 2, 3, 4,
3 min read
Kth Largest/Smallest Element in Binary Search Tree using JavaScript
A binary search tree is a type of binary tree in which each node has two children: left child & right child. In a Binary search tree (BST) all nodes in the left subtree have values less than the node value and all nodes in the right subtree have values greater than the node value. Different appr
4 min read
Detecting the Largest Element in an Array of Numbers (nested) in JavaScript
Given a nested array of numbers, we need to find and return the largest element present in the array. Below are the approaches to detecting the largest element in an array of Numbers (nested) in JavaScript: Table of Content Iterative ApproachRecursive ApproachIterative ApproachUse a nested loop to t
3 min read
JavaScript - Most Frequent Element in an Array
Let us talk about different methods to find the most frequent element in an array in JavaScript.Using JavaScript Object (For Small to Moderate Arrays)In this approach we use JavaScript object to store the number and their occurrences and find the element occurred most frequently.JavaScriptfunction m
3 min read
JavaScript Program to Find the First Non-Repeated Element in an Array
Finding the first non-repeated element in an array refers to identifying the initial occurrence of an element that does not occur again elsewhere within the array, indicating uniqueness among the elements.Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat i
5 min read
JavaScript Program to find Smallest and Largest Word in a String
We are going to discuss how can we find the Smallest and Largest word in a string. The word in a string which will have a smaller length will be the smallest word in a string and the word that has the highest length among all the words present in a given string will be the Largest word in a string.
5 min read
K-th Smallest Element after Removing some Integers from Natural Numbers using JavaScript
Given an array of size "n" and a positive integer k our task is to find the K-th smallest element that remains after removing certain integers from the set of natural numbers using JavaScript. Example:Input: array = [3, 5]k = 2Output: 2Explanation: The natural numbers are [1, 2, 3, 4, 5......] and a
5 min read
Remove Least Elements to Convert Array to Increasing Sequence using JavaScript
Given an array of numbers, our task is to find the minimum number of elements that need to be removed from the array so that the remaining elements form an increasing sequence. Examples: Input: arr = [5, 100, 6, 7, 100, 9, 8];Output: No of elements removed =3, Array after removing elements =[ 5, 6 ,
3 min read
JavaScript Program for the Minimum Index of a Repeating Element in an Array
Given an array of integers arr[], The task is to find the index of the first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. In this article, we will find the minimum index of a repeating element in an array in JavaScript.E
5 min read
JavaScript Program to Find N Largest Elements from a Linked List
This JavaScript program is designed to identify the N largest elements from a linked list. A linked list is a linear data structure where elements, known as nodes, are connected via pointers. The program iterates through the linked list to determine the N largest elements it contains. Table of Conte
4 min read