Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
Sorting arrays, probably rookie mistake

how are u? This is the thing, ive been trying to make a btn that order an array of products by price when the user clicks on it, but its not working, and i think is my ordering function using sort, cause i dont quite get sort function already, this is what im trying to do:

function ordmayorPrecio(arrprod) {
    arr = arrprod.sort(function (a,b){
    let precioa = parseInt(a.cost)
    let preciob = parseInt(b.cost)

    return precioa-preciob;
})
}

function ordmenorPrecio(arrprod) {
    arr = arrprod.sort(function (a,b){
    let precioa = parseInt(a.cost)
    let preciob = parseInt(b.cost)

    return preciob-precioa;
})
}

This is how im trying to make the buttons functional:

document.addEventListener("DOMContentLoaded", function (e) {
     getJSONData(PRODUCTS_URL)
    .then((result) => result.data)
    .then((productdata) => mostrarProductos(productdata));

    document.getElementById("sortDescPrice").addEventListener("click", function(){
        mostrarProductos(ordmenorPrecio(productdata));
    });

    document.getElementById("sortAscPrice").addEventListener("click",function(){
        mostrarProductos(ordmayorPrecio(productdata));
})

});

And this is how I try to append it to the HTML:

function mostrarProductos(arr){

    let productosAppend = '';

for(let i = 0; i < arr.length; i++){
        let producto = arr[i];

        productosAppend += `
            <a href="product-info.html" class="list-group-item list-group-item-action">
                <div class="row">
                    <div class="col-3">
                        <img src="` + producto.imgSrc + `" alt="` + producto.description + `" class="img-thumbnail">
                    </div>
                    <div class="col">
                        <div class="d-flex w-100 justify-content-between">
                            <h4 class="mb-1">`+ producto.name +`</h4>
                            <small class="text-muted">` + producto.soldCount + ` artículos</small>
                        </div>
                            <small class="text-muted">` + producto.cost + " " + producto.currency + ` </small>
                        <p class="mb-1">` + producto.description + `</p>
                        
                    </div>
                </div>
            </a>
            `
}
    document.getElementById("produto").innerHTML = productosAppend;
}


about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your sorting looks reasonable, assuming that the API returns an array of objects with a cost property. But you then need to return the sorted array:

function ordmayorPrecio(arrprod) {
    return arrprod.sort(function (a, b) {
        let precioa = parseInt(a.cost)
        let preciob = parseInt(b.cost)
        return precioa - preciob;
    })
}
function ordmenorPrecio(arrprod) {
    return arrprod.sort(function (a, b) {
        let precioa = parseInt(a.cost)
        let preciob = parseInt(b.cost)
        return preciob - precioa;
    })
}

The event listeners need to have a reference to the productdata argument from the .then - at the moment, they don't, they're referencing something outside instead (which may not even exist?). Add the listeners only after the response comes back.

document.addEventListener("DOMContentLoaded", function (e) {
    getJSONData(PRODUCTS_URL)
        .then((result) => result.data)
        .then((productdata) => {
            mostrarProductos(productdata);
            document.getElementById("sortDescPrice").addEventListener("click", function () {
                mostrarProductos(ordmenorPrecio(productdata));
            });
            document.getElementById("sortAscPrice").addEventListener("click", function () {
                mostrarProductos(ordmayorPrecio(productdata));
            })
        })
        .catch(handleErrors); // don't forget this part
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda