본문 바로가기
Js

sort, filter

by 영감은어디에 2024. 7. 1.
var products = [
    { id: 0, price: 5800, title: "학교종이 땡땡" },
    { id: 1, price: 3000, title: "동해물과" },
    { id: 2, price: 5500, title: "전국노래자랑" },
];

//가격정렬
$(".lowprice").on("click", function () {
    products.sort(function (a, b) {
        return a.price - b.price;
    });
    console.log(products);

    $(".row").html("");

    products.forEach(function (a, i) {
        prodlist(a, i);
    });
});

//상품명 역순
$(".namesort").on("click", function () {
    products.sort(function (a, b) {
        if (a.title < b.title) return 1;
        if (a.title > b.title) return -1;
        if (a.title === b.title) return 0;
    });
    console.log(products);

    $(".row").html("");

    products.forEach(function (a, i) {
        prodlist(a, i);
    });
});

// 5만원이하만
$(".price5").on("click", function () {
    var newproducts = products.filter(function (a) {
        return a.price <= 5000;
    });

    console.log(newproducts);

    $(".row").html("");

    newproducts.forEach(function (a, i) {
        prodlist(a, i);
    });
});

function prodlist(a, i) {
    var prodbox2 = `<div class="col-4">
            <img src="../img/1.jpg" class="w-100">
            <h5>${a.title}</h5>
            <p>가격 : ${a.price}</p>
        </div>`;
    $(".row").append(prodbox2);
}

products.forEach(function (a, i) {
    prodlist(a, i);
});

var btncount = 0;
$(".more").on("click", function () {
    btncount += 1;
    if (btncount == 1) {
        $.get("https://more1.json")
            .done(function (data) {
                data.forEach(function (a, i) {
                    prodlist(a, i);
                });
            })
            .fail(function () {});
    } else if (btncount == 2) {
        $.get("https://more2.json")
            .done(function (data) {
                data.forEach(function (a, i) {
                    prodlist(a, i);
                });
                $(".more").hide();
            })
            .fail(function () {});
    }
});

var arr = [5, 3, 7, 9, 45];
var arr2 = ["다", "가", "나"];
arr.sort(); // 문자형정렬
//숫자정렬
arr.sort(function(a,b){
    return a - b
});
//숫자역순
arr2.sort(function(b,a){
    return b - a;
})
//문자역순
arr2.sort(function(a, b) {
    if(a < b) return 1;
    if(a > b) return -1;
    if(a === b) return 0;
});

//filter
var 새어레이 = 어레이.filter(function(a){
    return 조건식
});
var 어레이 = [7,3,5,2,40];

var 새어레이 = 어레이.filter(function(a){
    return a < 4
});

'Js' 카테고리의 다른 글

gsap2  (0) 2024.07.05
gsap 1  (0) 2024.07.05
scroll  (0) 2024.07.04
scroll, clip-path  (0) 2024.07.04
ajax  (0) 2024.07.01
select, append, forEach  (0) 2024.07.01
array  (0) 2024.07.01
bubble  (0) 2024.07.01