In the
world of programming, an array is a type of data structure that helps to keep
multiple values or elements in one place. Arrays often have to find
different types of information, such as the minimum or maximum number. Today we
will learn how to find the minimum number from an array using JavaScript.
Problem
– Finding the minimum number from an array?
Example
with code explanation
function findMinimum(arr) {
return Math.min(...arr);
}
// Example usage
const numbers = [12, 5, 8, 20, 2, 15];
const minNumber = findMinimum(numbers);
console.log("The minimum number in the array is:", minNumber);
- Math.min function: This is a built-in function of JavaScript, which helps to find the minimum number from multiple numbers. For example, Math.min(3, 5, 1) will output 1.
- Spread
operator (...): Usually Math.min() cannot take an array directly. For this, we have
used the ... spread operator which separates the values of the
array. For example, [12, 5, 8] spreads the array into 12, 5, 8. As a result, the Math.min(...arr)
function can find the minimum value from each value in the array.
- Printing the result: We printed the minimum number using console.log, so that it is easy to see which number is the smallest in the array.
Method
2 –
function findMinimum(arr) {
let min = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
// Example usage
const numbers = [12, 5, 8, 20, 2, 15];
console.log("The minimum number in the array is:", findMinimum(numbers));
Method
3 –
function findMinimum(arr) {
return arr.reduce((min, num) => (num < min ? num : min));
}
// Example usage
const numbers = [12, 5, 8, 20, 2, 15];
console.log("The minimum number in the array is:", findMinimum(numbers));
Method
4 –
function findMinimum(arr) {
return arr.sort((a, b) => a - b)[0];
}
// Example usage
const numbers = [12, 5, 8, 20, 2, 15];
console.log("The minimum number in the array is:", findMinimum(numbers));
Bookmark the website! If you like the post and don't forget to share it with your friends so that they don't miss it. Be sure to like and comment so that we can constantly come up with new problems along with solutions and if you also have any coding-related problems, let us know in the comment box and we will try to solve them, InshaAllah.