javascript – How to show the team that scored the fewest goals?

Question:

I have the following

   let tabla = [{
        "equipo": "Barcelona FC",
        "pj": 35,
        "pg": 25,
        "pe": 8,
        "pp": 2,
        "pts": 83,
        "gf": 86,
    },

    {
        "equipo": "Atlético de Madrid",
        "pj": 35,
        "pg": 22,
        "pe": 8,
        "pp": 5,
        "pts": 74,
        "gf": 32,
    },
    {
        "equipo": "Ronaldo FC",
        "pj": 35,
        "pg": 22,
        "pe": 8,
        "pp": 5,
        "pts": 74,
        "gf": 12,
    },
    {
        "equipo": "Aleman casla",
        "pj": 35,
        "pg": 22,
        "pe": 8,
        "pp": 5,
        "pts": 74,
        "gf": 1,
    }];

What I want to do is show the team that scored the fewest goals, I made a function for that but it seems to me that what is failing is the if that is inside the for, how should that condition go?

function buscarmenor(tabla) {
        let menor = tabla[0].gf;
        for (let i = 0; i < tabla.length; i++) {
            if (tabla[i].gf < menor.gf) {
                menor = tabla[i].equipo
            }
        }
    }

Help is appreciated, the menor variable has to be the team name or a string .

Answer:

You can do it using the reduce method that applies an anonymous function whose parameters are the previous value and the current value. Simply comparing the previous one with the current one you can already obtain the minimum and / or the maximum.

That said, your function will look like this:

function buscarmenor(tabla) {
    let equipoMenor = tabla.reduce(function(prev, curr) {
        return prev.gf < curr.gf ? prev : curr;
    });

    return equipoMenor.equipo
}


console.log(buscarmenor(tabla))
Scroll to Top