# Array 정렬과 map, filter

이번에 낮은 가격순 정렬 버튼을 만들고 기능을 구현해볼껀데&#x20;

<figure><img src="/files/f0chLlXKrAILThew0rWG" alt=""><figcaption><p>낮은 가격순 정렬 예시</p></figcaption></figure>

그 전에 array 정렬하는 문법 부터 배워보자.

```javascript
var arr = [11,20,40,5,1];
arr.sort();  //문자정렬
console.log(arr);

arr.sort(function (a,b){
  return a - b
  //return 값이 양수면 a를 오른쪽으로
  //return 값이 음수면 b를 오른쪽으로
  //ex  a = 11 , b = 20
  //   11 - 20 = -9  20을 오른쪽으로
  
})

var arr2 = ['a', 'c', 'b'];
```

✨ 실습.  arr2 문자열 역순정렬 해보자.

## 코드 따라치지말고 위에서 배운  역순 정렬을 잘 고민해보자🤣

```javascript
arr.sort(function(a,b) {
    return b - a
});

console.log(arr);
```

```javascript
//가나다 순 정렬
arr2.sort(function(a,b){
    if(a < b){
        return 1
    }else {
        return -1
    }
});
```

✨ 실습. products 가격순 정렬 해보자.

가격순정렬 버튼을 상품더보기 버튼 위쪽에 만들어보자.

```html
<div class="container my-3">
    <button class="btn btn-danger" id="price">가격순정렬</button>
</div>

<script>
    $('#price').click(function (){
        products.sort(function (a,b){
            return a.price - b.price
        })
        console.log(products);
        //여기까지만 하면 화면은 안바뀌고 products 배열의 자료순서만 바뀜
        

        $('.row').html('');
        products.forEach(function (item,index){
            $('.row').append(`<div class="col-sm-4">
            <img src="https://via.placeholder.com/600" class="w-100">
            <h5>${item.title}</h5>
            <p>가격 : ${item.price}</p>
        </div>`)
        });
    });
</script>
```

## Array관련 함수

#### filter  - 조건에 맞는 자료만 남길 때

```javascript
var newArr = arr.filter(function (a){
    return a<10
})

console.log(newArr);   // [1,5]
```

#### map    - array 자료 전부 변형 할 때&#x20;

```javascript
var newArr2 = arr.map(function (a){

    return a*5
})

console.log(newArr2); //[5, 25, 55, 100, 200]
```

✨ 과제1.  상품명 다나가 순 정렬 버튼과 기능

✨ 과제2. 6만원 이하 상품만 보기 버튼과 기능


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeans-dev-book.gitbook.io/docs/lecture/javascript/array-map-filter.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
