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} );
};
2
Answers
You can use the
sort()
method of Array, which takes a callback function, which takes as parameters 2 objects contained in thearray
(which we call a and b)Loop starts after sorting
You need to send sort object in your express Request , but you have some errors in your code :
for example :
To get the selected value you can do it by your function in this mode :
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 :
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 :