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

357
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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