Home > Software design >  Trouble returning big and smallest number with a string output JavaScript
Trouble returning big and smallest number with a string output JavaScript

Time:09-11

I've been trying to solve a problem on a beginners testing site and I'm stuck on how to proceed. Can you please help with a complete block of code and any extra insight on where I'm going wrong so I can learn from it? Thank you.

If there is only one number in the array, that will be both the biggest and the smallest. If there are no numbers in the array, it should return an empty object. The answer must be like {biggest: 10750, smallest: 36} in terms of formatting.

What I got before my brain stopped working;

function findBigSmall(numbers) {
const highest = Math.max(...numbers);
const lowest = Math.min(...numbers);
`"biggest:" ${highest}, "smallest:" ${lowest}`
}

CodePudding user response:

  • If there is only one number within the array both Math.min() and Math.max() will return that number

  • If there aren't any numbers in the array, we can check if the array's length is 0, then return the empty object {}

function findBigSmall(numbers) {
  // Checking array's length and returning {} if empty
  if (numbers.length == 0) return {};
  // This will be executed if the previous 'if' didn't evaluate to true
  return { 
    biggest: Math.max(...numbers),
    smallest: Math.min(...numbers)
  };
}

console.log(findBigSmall([1,2,3,4,5]));
console.log(findBigSmall([]));
console.log(findBigSmall([1]));

Also, you're not assigning any variable to this: "biggest:" ${highest}, "smallest:" ${lowest} and if you assign a variable to this expression, the result will be a string not an object.

  • Related