Here is a sample of an array where i want to find the minimum from the .value in the array but when i try to do this which for loop it first give me the real minimum value but after it override with another value which not the minimum but the second last minimum
`
const AlzheimerData = [
{
"location": "world",
"year": "2000",
"value": "9.557819"
},
{
"location": "world",
"year": "2001",
"value": "10.267346"
},
{
"location": "world",
"year": "2002",
"value": "10.8148"
},
{
"location": "world",
"year": "2003",
"value": "11.329527"
}
]
var alzehemersmin = Number.MAX_VALUE;
for( data of AlzheimerData){
if(data.value < alzehemersmin){
alzehemersmin = data.value;
}
console.log(alzehemersmin);
}
output in console :
9.557819 --- Alzheimer.js:156:13 -- the real minimum value
10.267346 --- Alzheimer.js:156:13 -- the overided minimum value
I am expecting to get only the real minimum value which is the first one
3
Answers
Using the Math function may be an alternative;
It’s because you are comparing strings not floats. First, convert data.value to float and then compare them to find minimum.
This can be done in a one-liner:
Read more about: