All'alba vincerò

At dawn, I will win!

Javascript/Coding Apple

[Coding Apple] 가격순 정렬 / array 정렬 + array 함수

나디아 Nadia 2024. 3. 7. 00:15

 

 

array 정렬

 

 

숫자 정렬

오름차순

array.sort(function(a, b) { // a, b => array 안의 데이터 (ex. 7, 3)
    return a - b
    // (a-b)의 결과가 양수면 a는 오른쪽으로 이동
    // 음수면 b가 오른쪽으로 이동
});

 

 

내림차순

array.sort(function(a, b) { 
    return b - a
});

 

 

 

문자 정렬

오름차순

array.sort();

 

 

내림차순

array.sort(function(a, b) { 
    if (a > b) return -1; // 음수
    if (a < b) return 1; // 양수 
    return 0; // 같은 글자
});

 

 

 

array + object의 정렬 [ {  }, {  }, {  } ]

  • array.sort(); 사용
  • object.key로 접근
  products.sort(function(a, b) { // (a, b) => object
        return a.price - b.price
      // object.key
    });

 

 

 


 

array 함수

 

.filter( )

: array에서 원하는 자료 필터링하기

var 변수 = array.filter(function(a) { // 파라미터 -> array 안의 데이터
    return 조건식 // ex. a < 4
});
  • return 조건식에 어떤 자료를 남길건지 작성
  • filter( )의 결과는 변수에 저장해서 써야 함
  • 사용 예시: 특정 가격 미만/이상 상품 보여주기
  • .sort( ) - 원본 변형 O
    .filter( ) - 원본 변형 X

 

 

.map( )

: array 자료 전부 변형하기

var 변수 = array.map(function(a) { 
    return 조건식 // ex. a * 4
});
  • 사용 예시:  달러 가격을 원화로 보여주기

 

 


 

 

가격순 정렬

 

 

 

구현 계획 

1. 가격순 정렬
2. 카드 <div>의 기존 내용 삭제하기
3. 새로 정렬한 데이터 갯수만큼 카드 생성하기

var products = [
    { id : 0, price : 80000, title : 'Blossom Dress' },
    { id : 1, price : 50000, title : 'Spring Shirt' },
    { id : 2, price : 60000, title : 'Black pants' }
];


document.getElementById('price').addEventListener('click', function() {
    
    // 1. 가격순 정렬
    products.sort(function(a, b) { // (a, b) => object
        return a.price - b.price
    });

    // 2. 카드 div의 내용을 삭제하기
    document.querySelector('.row').innerHTML = '';
    
    // 3. 새로 정렬한 데이터 갯수만큼 카드 생성하기
    products.forEach((a, i) => {
        var a = 
            `<div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>${products[i].title}</h5> 
                <p>가격 : ${products[i].price}</p>
             </div>`;
    
        document.querySelector('.row').insertAdjacentHTML('beforeend', a);
    });
});

 

 

 

 

 

상품명 내림차순 정렬

 

 

구현 계획 

1. 상품명 내림차순 정렬
2. 카드 <div>의 기존 내용 삭제하기
3. 새로 정렬한 데이터 갯수만큼 카드 생성하기

document.getElementById('sort1').addEventListener('click', function() {

    // 1. 내림차순(다나가) 정렬
    products.sort(function(a, b) { 
        if (a.title < b.title) {
            return -1;
        } else {
            return -1
        }
    });

    // 2. 카드 div의 내용을 삭제하기
    document.querySelector('.row').innerHTML = '';

    // 3. 새로 정렬한 데이터 갯수만큼 카드 생성하기
    products.forEach((a, i) => {
        var a = 
            `<div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>${products[i].title}</h5> 
                <p>가격 : ${products[i].price}</p>
                </div>`;
    
        document.querySelector('.row').insertAdjacentHTML('beforeend', a);
    });
});

 

 

 

 

 

6만원 이하 상품만 보기

 

 

구현 계획 

1. 가격이 6만원 이하 필터링하기
2. 카드 <div>의 기존 내용 삭제하기
3. 새로 정렬한 데이터 갯수만큼 카드 생성하기

document.getElementById('filter').addEventListener('click', function() {

    // 1. 가격이 6만원 이하 필터링
    var newProduct = products.filter(function(a) {
        return a.price <= 60000
    })

    // 2. 카드 div의 내용을 삭제하기
    document.querySelector('.row').innerHTML = '';

    // 3. 새로 정렬한 데이터 갯수만큼 카드 생성하기
    newProduct.forEach((a, i) => {
        var a = 
            `<div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>${newProduct[i].title}</h5> 
                <p>가격 : ${newProduct[i].price}</p>
                </div>`;
    
        document.querySelector('.row').insertAdjacentHTML('beforeend', a);
    });
});

 

 

 

 

 

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <!-- Bootstrap CSS -->
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"/>
  </head>
  <body>
    
    <div class="container">
      <div class="row">
      </div>
    </div> 
    <div class="container my-3">
      <button class="btn btn-danger" id="price">가격순 정렬</button>
    </div>
    <div class="container my-3">
        <button class="btn btn-danger" id="sort1">다나가순 정렬</button>
      </div>
      <div class="container my-3">
        <button class="btn btn-danger" id="filter">6만원 이하</button>
      </div>
    <div class="container">
        <button class="btn btn-danger" id="more">더보기</button>
    </div>

    <script src="index.js"></script>
  </body>
</html>

 

 

 

index.js

var products = [
    { id : 0, price : 80000, title : 'Blossom Dress' },
    { id : 1, price : 50000, title : 'Spring Shirt' },
    { id : 2, price : 60000, title : 'Black pants' }
];

products.forEach((a, i) => {
    var a = 
        `<div class="col-sm-4">
            <img src="https://via.placeholder.com/600" class="w-100">
            <h5>${products[i].title}</h5> 
            <p>가격 : ${products[i].price}</p>
         </div>`;

        //     <h5>${a.title}</h5> 
        //     <p>가격 : ${a.price}</p>

    document.querySelector('.row').insertAdjacentHTML('beforeend', a);
});

//--------------------------------------------------
// 상품 더보기 버튼
let page = 1; // 가져올 페이지를 나타내는 변수

document.getElementById('more').addEventListener('click', function() {
    fetch(`https://codingapple1.github.io/js/more${page}.json`)
    .then(res => res.json())
    .then(data => {
        if (data.length > 0) { // 가져올 데이터가 있는 경우
            console.log(data);
            
            data.forEach(item => {
                let html = `
                <div class="col-sm-4">
                    <img src="https://via.placeholder.com/600" class="w-100">
                    <h5>${item.title}</h5> 
                    <p>가격 : ${item.price}</p>
                </div>`;
                
                document.querySelector('.row').insertAdjacentHTML('beforeend', html);
            });

            page++; // 다음 페이지로 설정
        } else { // 가져올 데이터가 없는 경우
            console.log("더 이상 데이터가 없습니다.");
            document.getElementById('more').disabled = true; // 더보기 버튼 비활성화
        }
    })
    .catch(error => {
        console.log(error);
    });
});

//--------------------------------------------------
// 가격순으로 정렬하기
document.getElementById('price').addEventListener('click', function() {
    
    // 1. 가격순 정렬
    products.sort(function(a, b) { // (a, b) => object
        return a.price - b.price
    });

    // 2. 카드 div의 내용을 삭제하기
    document.querySelector('.row').innerHTML = '';
    
    // 3. 새로 정렬한 데이터 갯수만큼 카드 생성하기
    products.forEach((a, i) => {
        var a = 
            `<div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>${products[i].title}</h5> 
                <p>가격 : ${products[i].price}</p>
             </div>`;
    
        document.querySelector('.row').insertAdjacentHTML('beforeend', a);
    });
});

//--------------------------------------------------
// 상품명 내림차순(다나가) 정렬
document.getElementById('sort1').addEventListener('click', function() {

    // 1. 내림차순(다나가) 정렬
    products.sort(function(a, b) { 
        if (a.title < b.title) {
            return -1;
        } else {
            return -1
        }
    });

    // 2. 카드 div의 내용을 삭제하기
    document.querySelector('.row').innerHTML = '';

    // 3. 새로 정렬한 데이터 갯수만큼 카드 생성하기
    products.forEach((a, i) => {
        var a = 
            `<div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>${products[i].title}</h5> 
                <p>가격 : ${products[i].price}</p>
                </div>`;
    
        document.querySelector('.row').insertAdjacentHTML('beforeend', a);
    });
});

//--------------------------------------------------
// 6만원 이하 상품만 보기
document.getElementById('filter').addEventListener('click', function() {

    // 1. 가격이 6만원 이하 필터링
    var newProduct = products.filter(function(a) {
        return a.price <= 60000
    })

    // 2. 카드 div의 내용을 삭제하기
    document.querySelector('.row').innerHTML = '';

    // 3. 새로 정렬한 데이터 갯수만큼 카드 생성하기
    newProduct.forEach((a, i) => {
        var a = 
            `<div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>${newProduct[i].title}</h5> 
                <p>가격 : ${newProduct[i].price}</p>
                </div>`;
    
        document.querySelector('.row').insertAdjacentHTML('beforeend', a);
    });
});

 

 

 


 

 

깃허브

https://github.com/kwonboryong/CodingApple/tree/main/array

 

 


 

 

출처

코딩애플

 

https://yooneeee.tistory.com/17