filter the name of an obj according to the highest number

Asked

Viewed 31 times

1

I got the program to show the highest value within an obj. However, the exercise asks me to disclose the name of the highest value obj.

let maior = 0;

for (let item of obras){
  if (maior < item.valor) {
    maior = item.valor;
  } if (item.valor = maior){
    console.log(item.nome);
  } 
} 

The second if this wrong, however I thought of nothing to solve it.

  • 2

    Instead of saving item.valor in maior, Isn’t it better to save the whole object? There if you compare maior.valor instead of just maior. And outside the for makes a console.log(maior.nome)

1 answer

2

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.