Home > Enterprise >  Javascript code first look at first number when sorting by price
Javascript code first look at first number when sorting by price

Time:08-31

let field = document.querySelector('.items');
let li = Array.from(field.children);

function SortProduct() {
    let select = document.getElementById('sortby');
    let ar = [];
    for(let i of li){
        const last = i.querySelector(".pop-price");
        const x = last.textContent.trim();
        const y = Number(x.substring(1));
        i.setAttribute("data-price", y);
        ar.push(i);
    }
}

select.onchange = sortingValue;

function sortingValue(){
            
    if (this.value === 'Default') {
        while (field.firstChild) {field.removeChild(field.firstChild);}
        field.append(...ar);    
    }
    if (this.value === 'lowtohigh') {
        SortElem(field, li, true)
    }
    if (this.value === 'hightolow') {
        SortElem(field, li, false)
    }
}

function SortElem(field,li, asc){
    let  dm, sortli;
    dm = asc ? 1 : -1;
    sortli = li.sort((a, b)=>{
        const ax = a.getAttribute('data-price');
        const bx = b.getAttribute('data-price');
        console.log(ax,bx);
        console.log(ax > bx  ? (1*dm) : (-1*dm));
        return ax > bx ? (1*dm) : (-1*dm);
        return ax , bx
    });
    while (field.firstChild) {field.removeChild(field.firstChild);}
    field.append(...sortli);    
    }
}

console.log(SortElem()) 

This is my JS code and when I try to sort by price my products first looks at first number and then other numbers. When I input 5, 20, 22, 25, 230 it sorts me like 20, 22, 230, 25, 5. I tried everything that comes in my mind nothing changed. Thanks for the help in advance.

CodePudding user response:

Your ax and bx might be strings. So, when you use > to compare them, you actually compare to string, such as "5" > "25" returns true

  • Related