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

355
Vistas
How sort objects according to value from select element?- mongodb, nodejs

I have to sort objects according to value from select option. How I should do this?

//This is my select element in another file

<select class="form-select" aria-label="Default select example">
  <option id="sorting" selected>Sort by</option>
  <option value="1">Low to High price</option>
  <option value="2">High to low price</option>
  <option value="3">From A to Z</option>
  <option value="4">From Z to A</option>
</select>

//And code with my sort function

 module.exports.listOfHouses = async (req, res) => {
        
        function selectedValue(){
            if(document.getElementById("sorting").value === "1"){
                return "title: 1"
            } else if(document.getElementById('sorting').value == "2"){
            return "title: 1"
        }else if(document.getElementById('sorting').value == "3"){
            return "title: 1"
        }else if(document.getElementById('sorting').value == "4"){
            return "title: 1"
        } else {
            return "title: 1"
        }
    }
        const houses = await House.find({}).sort({selectedValue});
        res.render('houses/houses', {houses} );
    };
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b)

listOfHouses.sort((a, b) => (a.value > b.value) ? 1 : -1)

Loop starts after sorting

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to send sort object in your express Request , but you have some errors in your code :

  • to get a value from DOM select element you need to add id to the select element not to option. for example :
<select id="sorting" class="form-select" aria-label="Default select example">
  <option selected>Sort by</option>
  <option value="1">Low to High price</option>
  <option value="2">High to low price</option>
  <option value="3">From A to Z</option>
  <option value="4">From Z to A</option>
</select>

To get the selected value you can do it by your function in this mode :

function getSortingObject() {


    const value = document.getElementById("sorting").value

    if (document.getElementById("sorting").value === "1") {
        return {price:1}
    } else if (document.getElementById('sorting').value == "2") {
        return {price:-1}
    } else if (document.getElementById('sorting').value == "3") {
        return "title: 1"
    } else if (document.getElementById('sorting').value == "4") {
        return {title:1}
    } else {
        return {title:-1}
    }
}

Now you need to send the current sorting object from your front-end to your backend so you need to get the sorting object in this mode :

const sortingObject = getSortingObject()

fetch(YOUR URL,YOUR_BODY WITH Sorting object )

In the backend you need to validate thet the sorting object is allowed to be used ar coded the allowed pros to sort in this mode :

 module.exports.listOfHouses = async (req, res) => {
    const canSortBy = ["title","price"]
    const sortingoBJECT = req.body.sortingObject
 
    const canSort = Object.keys(sortingoBJECT).findIndex(r=>!canSortBy[r])
    if(canSort) res.sendStatus(....)




     const houses = await House.find({}).sort(sortingoBJECT);
     res.render('houses/houses', {
         houses
     });
 };

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