Using the ideas of @Rafael Tavares, one way to solve it would be:
const obras = [
{valor: 1,
nome: "um"},
{valor: 2,
nome: "dois"}
]
if (obras.length > 0) {
let maior = obras[0]
for (let i = 1; i < obras.length;i++){
if (obras[i].valor > maior.valor) {
maior = obras[i]
}
}
console.log(`A obra de maior valor é: ${maior.nome}`)
} else {
console.log('Não é possível determinar o maior valor')
}
In my code I am checking the size of the works set before I can determine the largest.
This is important because if the set is empty I cannot determine what the highest value is. In your example you are assigning a zero value to the variable"maior" that is not part of the set of works, which in this case can give a false positive. Imagine that in the set there are only negative values, in this case your program will display a wrong value.
Another thing I did was to assign the work value[0] to the larger variable, and start the iteration (repetition) from the second element. (usually the loop for starts with zero index).
So by going through the entire dataset we have the expected result.
Instead of saving
item.valorinmaior, Isn’t it better to save the whole object? Thereifyou comparemaior.valorinstead of justmaior. And outside theformakes aconsole.log(maior.nome)– Rafael Tavares