I'm going to add filter which would be sorting shop products by the price. I didn't know how exactly I should do that so I found the code but something is wrong cos it doesn't work property. products are not set from lowest to highest:
First is my index.js which shows all my products and objects
module.exports = ({ products }) => {
const renderedProducts = products
.map(product => {
return `
<div data-price="" class="image shopProduct ${product.category.join(' ')} ${product.fabric.join(' ')} ${product.bulb}" >
<img class="" src="data:image/png;base64, ${product.image}"/>
<h3 class="subtitle">${product.title} <br>${product.model}</h3>
<h5 >${product.price.toFixed(2)} zł</h5>
<form action="/cart/products" method="POST">
<input hidden value="${product.id}" name="productId" />
<button class="button has-icon is-inverted">Dodaj do
<i class="fa fa-shopping-cart"></i></button>
</form>
</div>
</div>
<select class="sorting">
<option value="Sort">Sortuj</option>
<option value="SortA">Nazwa A-Z</option>
<option value="Sort">Nazwa Z-A</option>
<option value="high">Cena rosnąco</option>
<option value="low">Cena malejąco</option>
</select>
//This is my javascript code
<script>
let field = document.querySelector('.images');
let div = Array.from(field.children)
let select = document.querySelector('.sorting');
let ar=[];
for (let i of div){
const h3 = i.children[2];
const x = h3.innerHTML.trim();
const y = Number(x);
i.setAttribute('data-price', y);
ar.push(i);
}
select.onchange = sorting;
function sorting() {
if(this.value === "Sort") {
while(field.firstChild){
field.removeChild(field.firstChild);
}
field.append(...ar)
}
if(this.value === "high"){
sortElement(field, div, true);
}
if(this.value === "low"){
sortElement(field, div, false);
}
}
function sortElement(field, div, asc){
let dm, sortDiv;
dm = asc ? 1 : -1;
sortDiv = div.sort((a, b) => {
const ax = a.getAttribute('data-price');
const bx = b.getAttribute('data-price');
return ax > bx ? (1*dm) : (-1*dm) ;
})
while(field.firstChild){
field.removeChild(field.firstChild);
}
field.append(...sortDiv)
}
</script>```