0

I'm trying to get the minimum value from an array in Vue3 but I keep getting an infinity value. Can I please get help?

Below is adding value to the 'ranks' array.

const ranks = ref([])
for (let i = 0; i < uni.value.length; i++) {
    ranks.value.push(uni.value[i].rank)
}

And here is the finding min code:

const min = Math.min(...ranks.value)
console.log(min)  // it returns Infinity

this is how my ranks array looks in the console:

ranks array in console

rakeshboliya
  • 103
  • 12
  • You get Infinity if your ranks array is empty. Check if the for loop is actually correctly filling the ranks array. – Gabe Aug 08 '22 at 06:13
  • the image above is the result of console.log(ranks.value). It shows that there are 3 elements in an array. So I thought adding elements worked fine. – Jihwan Shin Aug 08 '22 at 06:19
  • If you open target in that console.log, what is in it? It might be 3 ‘undefined’ values. – Gabe Aug 08 '22 at 06:30
  • I edited my image above – Jihwan Shin Aug 08 '22 at 06:34
  • Does this answer your question? [Get max and min value from array in JavaScript](https://stackoverflow.com/questions/11985341/get-max-and-min-value-from-array-in-javascript) – Michal Levý Aug 08 '22 at 06:38
  • You do not need the spread operator (...) then calling `Math.min()`. Or you should calll `Math.min([...ranks.value])`. – Gabe Aug 08 '22 at 06:45
  • (`Math.min([...ranks.value])`) returned 0!! Although it is not the answer that I want (should be 1) I got something! – Jihwan Shin Aug 08 '22 at 06:52
  • Btw, both (`ranks[0]`) and (`ranks.value[0]`) returned undefined. Maybe this is why I keep getting Infinity value??? – Jihwan Shin Aug 08 '22 at 06:53
  • Can you copy the object and share it @JihwanShin... – Sujith Sandeep Aug 08 '22 at 07:38
  • Yeah, that’s what I thought earlier. If the ranks are undefined you get the Infinity outcome. It should be in the for loop and the value of the uni object you are using. Try to log what you push into the ranks array. – Gabe Aug 08 '22 at 08:29

2 Answers2

0
const minValue = (nums) => {
  let min = Infinity; 
  for(let i=0; i< nums.length;i++){
    if(min > nums[i]){
      min = nums[i];
    }
  }
  return min;
};
Anudeep GI
  • 931
  • 3
  • 14
  • 45
0

Use the below code to find the minimum value.

a = [5,4,1,2,3]
let minVal = Infinity
a.forEach(val => minVal = minVal > val ? val : minVal)
console.log('Minimum value is ' + minVal)
Sujith Sandeep
  • 1,185
  • 6
  • 20