Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Remove smallest number in Array JavaScript
In JavaScript, removing the smallest number from an array can be accomplished in several ways. This article demonstrates different approaches to find and remove the smallest element from an array in place.
Method 1: Using reduce() and splice()
This approach uses reduce() to find the index of the smallest element, then splice() to remove it:
const arr = [2, 1, 3, 2, 4, 5, 1];
const removeSmallest = arr => {
const smallestCreds = arr.reduce((acc, val, index) => {
let { num, ind } = acc;
if (val >= num) {
return acc;
}
ind = index;
num = val;
return { ind, num };
}, {
num: Infinity,
ind: -1
});
const { ind } = smallestCreds;
if (ind === -1) {
return;
}
arr.splice(ind, 1);
};
removeSmallest(arr);
console.log(arr);
[ 2, 3, 2, 4, 5, 1 ]
Method 2: Using Math.min() and indexOf()
A simpler approach using built-in methods to find the minimum value and its index:
const arr2 = [2, 1, 3, 2, 4, 5, 1];
const removeSmallestSimple = arr => {
if (arr.length === 0) return;
const minValue = Math.min(...arr);
const minIndex = arr.indexOf(minValue);
arr.splice(minIndex, 1);
};
console.log("Before:", arr2);
removeSmallestSimple(arr2);
console.log("After:", arr2);
Before: [ 2, 1, 3, 2, 4, 5, 1 ] After: [ 2, 3, 2, 4, 5, 1 ]
Method 3: Using findIndex() with Math.min()
Another clean approach combining findIndex() with Math.min():
const arr3 = [5, 3, 8, 1, 2];
const removeSmallestWithFindIndex = arr => {
if (arr.length === 0) return;
const minValue = Math.min(...arr);
const minIndex = arr.findIndex(val => val === minValue);
arr.splice(minIndex, 1);
};
console.log("Original:", arr3);
removeSmallestWithFindIndex(arr3);
console.log("Modified:", arr3);
Original: [ 5, 3, 8, 1, 2 ] Modified: [ 5, 3, 8, 2 ]
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
| reduce() + splice() | O(n) | Complex | Learning array methods |
| Math.min() + indexOf() | O(n) | Simple | Most practical cases |
| findIndex() + Math.min() | O(n) | Clean | Modern JavaScript |
Key Points
- All methods remove only the first occurrence of the smallest number
- Always check for empty arrays to avoid errors
-
Math.min()with spread operator is the most readable approach - These methods modify the original array in place
Conclusion
The Math.min() with indexOf() approach is recommended for its simplicity and readability. Use reduce() when you need more control over the comparison logic.
Advertisements
