How to use Math.min and filter() In Javascript
Find the minimum value in the array using Math.min
and exclude the smallest element using filter method
.
Example: This JavaScript code uses filtering to exclude the smallest element and then finds the minimum of the remaining array, effectively determining the second smallest element.
function secondSmallest(arr) {
const smallest = Math.min(...arr);
const filteredArray = arr
.filter(num => num !== smallest);
return Math.min(...filteredArray);
}
console.log(secondSmallest([1, 12, 13, 2,]))
Output
2
Find Second Smallest Element in an Array in JavaScript
JavaScript allows us to compute the Second Smallest Element within a given array. The task involves iterating through the array, identifying the smallest and second smallest element in the array.
There are several approaches to finding the second smallest element in an array using Javascript which are as follows:
Table of Content
- Using Sort method()
- Using iteration
- Using Math.min and filter()