1. 문자열 배열 정렬(알파벳)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<p id="demo"></p>
 
<button onclick="myFunction()">Try it</button>
 
<script>
    var fruits = ["Banana""Orange""Apple""Mango"];
    
//    console.log("console> fruits.length : " + fruits.length);
 
    document.getElementById("demo").innerHTML = fruits;
    
//     sort() : 배열 요소를 알파벳 순서대로 정렬
//     reverse() : 알파벳 역순으로 정렬    
     function myFunction() {
         fruits.sort();
         fruits.reverse();
        
         document.getElementById("demo").innerHTML = fruits;
     }        
</script>
 
</body>
</html>
cs

 

 

2. 숫자 배열 정렬

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<p id="demo"></p>
 
<button onclick="myFunction()">Try it</button>
 
<script>
    var points = [40100152510];
    
//    console.log("console> points.length : " + points.length);
 
    document.getElementById("demo").innerHTML = points;
    
    function myFunction() {
//        sort() : 배열 요소를 알파벳 순서대로 정렬하는 메소드
//                 숫자가 올 경우 안에 callback 함수를 이용하여 정렬
//        숫자를 작은 수 > 큰 수 순으로 정렬하는 경우
        points.sort(function(a, b) {
            return a - b;
        });
 
//        숫자를 큰 수 > 작은 수 순으로 정렬하는 경우
        points.sort(function(a, b) {
            return b - a;
        });
        
        document.getElementById("demo").innerHTML = points;
    }
</script>
 
</body>
</html>
cs

+ Recent posts