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

10
  • You get Infinity if your ranks array is empty. Check if the for loop is actually correctly filling the ranks array. Commented Aug 8, 2022 at 6: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. Commented Aug 8, 2022 at 6:19
  • If you open target in that console.log, what is in it? It might be 3 ‘undefined’ values. Commented Aug 8, 2022 at 6:30
  • I edited my image above Commented Aug 8, 2022 at 6:34
  • Does this answer your question? Get max and min value from array in JavaScript Commented Aug 8, 2022 at 6:38

2 Answers 2

0
const minValue = (nums) => {
  let min = Infinity; 
  for(let i=0; i< nums.length;i++){
    if(min > nums[i]){
      min = nums[i];
    }
  }
  return min;
};
Sign up to request clarification or add additional context in comments.

1 Comment

console.log(minValue(ranks)) should give me the minimum value, right?
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)

4 Comments

Your code works when the array is predefined like above. But, my array is in ref (I'm not sure if this makes any difference), and when I run code "ranks.forEach(val => minVal = minVal > val ? val : minVal)", it throws an error saying "ranks.forEach is not a function".
You should use ranks.value.forEach since you are using a ref.
hmm.... it still returns infinity.
Yes, see my other comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.