Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda