0

I am trying to write a function that finds the smallest integer of an array, and was hoping that it would be as easy as dropping a Math.min() in there.

However, after looking this up and playing around with a few things, I cannot for the life of me figure out what the parameters are supposed to be.

The below was my first stab. I am aware that some methods dont require parameters (well I think I know, im a complete beginner)

/* function findSmallestInteger(arr) {
    const newArr = arr.Math.min();
    return newArr
}

Than this was my second.

function findSmallestInteger(func, arr) {
    return arr.Math.min(arr)
}

I would like the function output to take an array and simply spit out the smallest integer in that array.

Any pointers are much appreciated

acz19
  • 1
  • 1
  • sort and then `arr[0]`? – depperm Dec 15 '22 at 13:57
  • 3
    [The documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) provides an example using an array... `return Math.min(...arr)` – David Dec 15 '22 at 13:59

1 Answers1

-2

You have to call Math.min multiple times on all the elements (if the array is ordered you can do binary search but keep it simple). Here I generate a random array of ten elements, you can skip this part. Inside the function I use reduce that exec Math.min on all the couples of elements of the array. If you don't know reduce, you can implement a more naif solution with a classic for or a for-of.

Furthermore you can extend class Math and override Math.min behavior ,in this way providing your implementatio you can allow Math.min to work with arrays too. If this is the case I can show you how you can do but you have to know Es6 and OOP concept like class and inheritance (more advanced stuff)

let array = Array.from({ length: 10 }, () => Math.floor(Math.random() * 50));
console.log(array)
console.log(findSmallestInteger(array))


function findSmallestInteger(array){
    return array.reduce((accumulator,currentValue) => 
    Math.min(accumulator,currentValue),array[0])
}
Nick
  • 1,439
  • 2
  • 15
  • 28