• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 JavaScript, TS 게시판 Javascript sort 질문

Javascript sort 질문

5 글 보임 - 1 에서 5 까지 (총 5 중에서)
  • 글쓴이
  • #127164

    강승우
    참가자
    가나다 정렬 코드를 짜다가 질문이 생겼습니다
    
    
    var products = [
    { id: 0, price: 70000, title: 'Blossom Dress' },
    { id: 1, price: 50000, title: 'Springfield Shirt' },
    { id: 2, price: 60000, title: 'Black Monastery' }
    ];
    var allProducts = [...products]; // 모든 로드된 제품을 저장하는 배열
    var btn_click = 0;
    // 제품 HTML 템플릿 생성 함수
    function generateTemplate(product) {
    return `
     <div class="col-sm-4">< img src="https://via.placeholder.com/600" class="w-100">
     <h5>${product.title}</h5>
     <p>가격 : ${product.price}</p></div>`;
    }
    // 제품 목록 업데이트 함수
    function updateProductList(products) {
     products.forEach((product) => {
    var template = generateTemplate(product);
    $('.row').append(template);
    });
    }
    // 초기 제품 목록 업데이트
    $(document).ready(function () {
    $('.row').html('');
    updateProductList(products);
    // console.log(products)
    $('#more').click(function () {
     btn_click += 1;
    if (btn_click == 1) {
    loadMoreProducts('https://codingapple1.github.io/js/more1.json');
    } else if (btn_click == 2) {
    $('#more').addClass('btn-hide');
    loadMoreProducts('https://codingapple1.github.io/js/more2.json');
    }
    });
    // 가격순 정렬
    $('#sort_price').click(function () {
     allProducts.sort(function (a, b) {
     console.log(a, b)
    return a.price - b.price;
    });
    $('.row').html('');
    updateProductList(allProducts);
    });
    // 가나다 정렬   여기가 문제문제문제문제!!!!!!!!!
    $('#sort_msg').click(function() {
     allProducts.sort(function(a, b) {
    if ( a.title > b.title) {
    return 1;
    }
    if (a.title < b.title) {
    return -1;
    }
    })
    // console.log(allProducts)
     
    $('.row').html('');
    updateProductList(allProducts);
    })
    });
    
    
    // 더 많은 제품을 로드하는 함수
    function loadMoreProducts(url) {
     $.get(url).done(function (data) {
     allProducts = allProducts.concat(data); // 새로운 데이터를 기존 데이터에 추가
    updateProductList(data);
    });
    }
    
    현재 코드는 저렇게 되어있지만 
    강의에서 가나다 정렬은
    var 어레이2 = ['다', '가', '나'];
    어레이2.sort();
    이렇게 했습니다.
    하지만 코드상에서
    allProducts.sort();
    이렇게 하면 작동하지 않습니다. 
    
    
    #127169

    codingapple
    키 마스터
    복붙해보니까 버튼2개누르면 array 정렬은 각각 잘되는거같습니다
    html이 이상하거나 html에 꽂는 코드가 뭔가 이상한게 아닐까요
    #127181

    강승우
    참가자
    임의로 다나가 정렬을 반대로 해서 가나다 정렬을 하긴 했지만 저렇게 하는게 맞나요?
    #127184

    강승우
    참가자
    var 어레이2 = ['다', '가', '나'];
    어레이2.sort();
    console.log(어레이2); 했을때 "가, 나 다" 이렇게 정렬이 되었는데
    
    제가짠 코드에서
    allProducts.sort();
    console.log(allProducts) 했을때는 정렬되지 않습니다.
    #127206

    codingapple
    키 마스터
    var products = [
    { id: 0, price: 70000, title: 'Blossom Dress' },
    { id: 1, price: 50000, title: 'Springfield Shirt' },
    { id: 2, price: 60000, title: 'Black Monastery' }
    ];
    var allProducts = [...products];
    
    allProducts.sort(function(a, b) {
      if ( a.title > b.title) {
      return 1;
      }
      if (a.title < b.title) {
      return -1;
      }
    })
    console.log(allProducts)
    넴 이러면 가나다 정렬 잘됩니다
5 글 보임 - 1 에서 5 까지 (총 5 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠