To find the smallest integer in an array, we can use various methods. Firstly, let’s use the Math.min() method:
let arr = [23, -3, 0, 1, 78, 66, 1000];
let smallestInt = Math.min(...arr);
console.log(smallestInt);
// returns -3 to the console
Using reduce() method:
let arr = [0,-4,89,678,1000,-44];
let result = arr.reduce(function(prev, curr) {
return prev < curr ? prev : curr;
});
console.log(result);
// returns -44
Let’s break down Example 2 now using some visuals for you to understand:
We have [0,-4,89,678,1000,-44].
We have 'prev' and 'curr' in a sort of a recursion here.
Now, in [0,-4], -4 is the smallest.
In [-4,89], -4 is the smallest.
In [-4,678], -4 is the smallest.
In [-4,1000], again -4 is the smallest.
Finally, in [-4,-44], -44 is the smallest.
// Hence, the method returns -44.
Other ways to do this:
findSmallestInteger = arr => Math.min(...arr);
findSmallestInteger([2,3,4,5,6,7,8]);
// outputs 2
const args = [23,4,56,77,2];
const result = args.reduce((a, b) => b < a ? b : a, +Infinity);
console.log(result);
// outputs 2