-4

I am facing problem with my question below which restricted us to use Math.Min() function to obtain answer. I tried multiple ways but never seems to get the answer right.

Minimum of two numbers Let's pretend the JavaScript Math.min() function doesn't exist. Complete the following program so that the min() function returns the minimum of its two received numbers.

// TODO: write the min() function

console.log(min(4.5, 5)); // Must show 4.5

console.log(min(19, 9)); // Must show 9

console.log(min(1, 1)); // Must show 1

Kaiyoung
  • 1
  • 1
  • 3
    Does this answer your question? [Find smallest value in Array without Math.min](https://stackoverflow.com/questions/19432769/find-smallest-value-in-array-without-math-min) – aerial Dec 14 '21 at 06:27
  • 1
    _". I tried multiple ways but never seems to get the answer right"_ - Please provide some code that shows us what you have tried (also see: [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822)) – Nick Parsons Dec 14 '21 at 06:31
  • Also this: https://stackoverflow.com/a/33851891/17175441 – aerial Dec 14 '21 at 06:33

4 Answers4

2

One-liner using .reduce():

const min = (...args) => args.reduce((min, num) => num < min ? num : min, args[0]);

console.log(min(1, 3, 4, 5, 6, 0.5, 4, 10, 5.5));
console.log(min(12, 5));
Xeelley
  • 1,081
  • 2
  • 8
  • 18
-1

You can try this

function getMin(a,b) {
  var min = arguments[0];
   for (var i = 0, j = arguments.length; i < j; i++){
        if (arguments[i] < min) {
             min = arguments[i];
         }
    }
  return min;
}

console.log(getMin(-6.5,4));
  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – holydragon Dec 14 '21 at 06:53
  • Thanks, will keep in mind for for future post – zokizuan Dec 14 '21 at 15:14
-1
function min(n1,n2) {
if (n1 < n2) {
    return n1;
} else if ( n2 < n1) {
    return n2;
} else {
    return n1 || n2;
}
}
console.log(min(19,9)); //prints 9 because of the else if statement
console.log(min(1,1));  // prints either because of the else statement
console.log(min(4.5,5)); //prints 4.5 because of the if statement

or to simplify:

function min(n1, n2) {
if (n1 < n2) return n1
return n2
}

This will not win awards for elegance or accuracy but I simply followed the instructions and it worked... (not a programmer)

dranoelrn
  • 1
  • 1
-4
const min = (a, b) => {
 let arr = [a, b];
 return arr.sort((a, b) => a - b)[0];
};

console.log(min(4.5, 5)); // 4.5

this min() function sorts the array and returns the first element. this should return the smallest element. example:
min([2, 3]) -> 2
min([4.5, 9]) -> 4.5