본문 바로가기

Front End/Javascript

[JavaScript] 배열에서 최대값/최소값 구하기

난수로 배열 채우기

let getRandomNumber = (min, max) => parseInt(Math.random() * (max - min + 1)) + min;
let ar = [];
for (let i = 0; i < 10; i++) ar.push(getRandomNumber(0, 100));
console.log(ar); 

 

가장 전통적인 방법으로 최대값 최소값 구하기

let max = ar[0], min = ar[0];
for (let i = 0; i < ar.length; i++) {
    if (max < ar[i]) max = ar[i];
    if (min > ar[i]) min = ar[i];
}
console.log(`최대값 : ${max}, 최소값 : ${min}`); 

 

for~in 사용 : index가 넘어온다.

let max = ar[0], min = ar[0];
for (let i in ar) {
    if (max < ar[i]) max = ar[i];
    if (min > ar[i]) min = ar[i];
}
console.log(`최대값 : ${max}, 최소값 : ${min}`); 

 

for~of 사용 : 값이 넘어온다.

if문을 사용해서 구하기

for (let n of ar) {
    if (max < n) max = n;
    if (min > n) min = n;
}
console.log(`최대값 : ${max}, 최소값 : ${min}`); 

 

삼항연산자를  사용해서 구하기

for (let n of ar) {
    max = max < n ? n : max;
    min = min > n ? n : min;
}
console.log(`최대값 : ${max}, 최소값 : ${min}`); 

 

Math.max(), Math.min() 메서드를   사용해서 구하기

for (let n of ar) {
    max = Math.max(max, n);
    min = Math.min(min, n);
}
console.log(`최대값 : ${max}, 최소값 : ${min}`);

 

forEach() 메서드를 사용해서 구하기

ar.forEach((n)=>{
    max = Math.max(max, n);
    min = Math.min(min, n);
});
console.log(`최대값 : ${max}, 최소값 : ${min}`);

 

다음과 같이 하면 NaN을 반환한다.

max = Math.max(ar);
min = Math.min(ar);
console.log(`최대값 : ${max}, 최소값 : ${min}`);

 

전개 연산자(spread  operator) 를 사용해서 구하기

max = Math.max(...ar);
min = Math.min(...ar);
console.log(`최대값 : ${max}, 최소값 : ${min}`);

 

Function.prototype.apply() 메소드는 Javascript에서 함수를 호출하는 여러가지 방법 중의 하나입니다.
일반적으로 함수를 호출할 때, 함수명(파라미터)'의 형식으로 호출하지만, 함수의 apply() 메소드를 호출해서 함수를 호출할 수도 있습니다.
apply() 메소드는 첫번째 파라미터로, 함수에서 사용할 this객체와 호출하는 함수로 전달할 파라미터를 입력받습니다.
이 때 apply() 메소드의 2번째 파라미터(호출하는 함수로 전달할 파라미터)는 배열 형태로 입력합니다.

max = Math.max.apply(null, ar);
min = Math.min.apply(null, ar);
console.log(`최대값 : ${max}, 최소값 : ${min}`);


Math.max() 함수의 apply() 메소드를 호출하고 있습니다.
apply() 메소드의 첫번째 파라미터로는 Math.max() 함수 내부에서 사용할 this객체를 전달해야 하는데, 여기서는 따로 this객체를 지정해 줄 필요가 없으므로 null을 전달하였습니다.
apply() 메소드의 두번째 파라미터로는 Math.max() 함수로 전달할 파라미터를 배열 형태로 넣어주면 됩니다.

 

객체에 대해서도 가능하다.

fruits = [
    {id: 101, fruit: "사과", price: 10000, qty: 5 },
    {id: 102, fruit: "딸기", price: 8000, qty: 15 },
    {id: 103, fruit: "복숭아", price: 15000, qty: 6 },
    {id: 104, fruit: "바나나", price: 3000, qty: 8 },
    {id: 105, fruit: "메론", price: 30000, qty: 4 },
    {id: 106, fruit: "수박", price: 22000, qty: 5 },
    {id: 107, fruit: "참외", price: 4000, qty: 9 },
    {id: 108, fruit: "체리", price: 6000, qty: 33 },
    {id: 109, fruit: "포도", price: 7000, qty: 21 },
    {id: 110, fruit: "배", price: 4000, qty: 18 },
  ]
 
for(let obj of fruits){
    console.log(obj);
}

 

객체배열 중에서 특정 특정 열만 추출하기

// 객체배열 중에서 이름만 추출하기 
let
fruit_names = fruits.map(({fruit, ...another})=> fruit);
console.log(fruit_names);

// 객체배열 중에서 가격만 추출하기
let fruit_price = fruits.map(({price, ...another})=> price);
console.log(fruit_price)

 // 객체배열 중에서 이름과 가격만  추출하기
let name_price = fruits.map(({name, qty, id, ...another})=> another);
console.log(name_price)

console.log(`최고가 과일 가격 : ${Math.max(...fruits.map(({price})=> price))}`);
console.log(`최저가 과일 가격 : ${Math.min(...fruits.map(({price})=> price))}`);

// 출력
// 최고가 과일 가격 : 30000
// 최저가 과일 가격 : 3000

 

최고과 과일과 최저자 과일을 구해보자

max = fruit_price[0];
min = fruit_price[0];
let max_index, min_index;
for (let i in fruit_price) {
    if (max < fruit_price[i]){
        max = fruit_price[i];
        max_index = i;
    }
    if (min > fruit_price[i]){
        min = fruit_price[i];
        min_index = i;
    }
}
console.log(max_index + " : " + min_index)
console.log(`최대값 : ${max}, 최소값 : ${min}`);
console.log(`최고가 과일 : ${JSON.stringify(fruits[max_index])}`);
console.log(`최저가 과일 : ${JSON.stringify(fruits[min_index])}`);


// 출력
// 최고가 과일 : {"id":105,"fruit":"메론","price":30000,"qty":4}
// 최저가 과일 : {"id":104,"fruit":"바나나","price":3000,"qty":8}

 

 

min_max.html 파일을 만들자

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>최대값/최소값 구하기</title>
    <script>
        let getRandomNumber = (min, max) => parseInt(Math.random() * (max - min + 1)) + min;
        let ar = [];
        for (let i = 0; i < 10; i++) ar.push(getRandomNumber(0100));
        console.log(ar);
 
        let max = ar[0], min = ar[0];
        for (let i = 0; i < ar.length; i++) {
            if (max < ar[i]) max = ar[i];
            if (min > ar[i]) min = ar[i];
        }
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        for (let i in ar) {
            if (max < ar[i]) max = ar[i];
            if (min > ar[i]) min = ar[i];
        }
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        for (let n of ar) {
            if (max < n) max = n;
            if (min > n) min = n;
        }
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        for (let n of ar) {
            max = max < n ? n : max;
            min = min > n ? n : min;
        }
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        for (let n of ar) {
            max = Math.max(max, n);
            min = Math.min(min, n);
        }
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        ar.forEach((n)=>{
            max = Math.max(max, n);
            min = Math.min(min, n);
        });
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        max = Math.max(ar);
        min = Math.min(ar);
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        max = Math.max(...ar);
        min = Math.min(...ar);
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        max = Math.max.apply(null, ar);
        min = Math.min.apply(null, ar);
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
 
        fruits = [
            {id: 101, fruit: "사과", price: 10000, qty: 5 },
            {id: 102, fruit: "딸기", price: 8000, qty: 15 },
            {id: 103, fruit: "복숭아", price: 15000, qty: 6 },
            {id: 104, fruit: "바나나", price: 3000, qty: 8 },
            {id: 105, fruit: "메론", price: 30000, qty: 4 },
            {id: 106, fruit: "수박", price: 22000, qty: 5 },
            {id: 107, fruit: "참외", price: 4000, qty: 9 },
            {id: 108, fruit: "체리", price: 6000, qty: 33 },
            {id: 109, fruit: "포도", price: 7000, qty: 21 },
            {id: 110, fruit: "배", price: 4000, qty: 18 },
        ]
        
 
        console.log(JSON.stringify(fruits));
 
        let fruit_names = fruits.map(({fruit, ...another})=> fruit);
        console.log(fruit_names);
        let fruit_price = fruits.map(({price, ...another})=> price);
        console.log(fruit_price)
        let name_price = fruits.map(({name, qty, id, ...another})=> another);
        console.log(name_price)
 
        console.log(`최고가 과일 가격 : ${Math.max(...fruits.map(({price})=> price))}`);
        console.log(`최저가 과일 가격 : ${Math.min(...fruits.map(({price})=> price))}`);
 
        max = fruit_price[0];
        min = fruit_price[0];
        let max_index, min_index;
        for (let i in fruit_price) {
            if (max < fruit_price[i]){
                max = fruit_price[i];
                max_index = i;
            } 
            if (min > fruit_price[i]){
                min = fruit_price[i];
                min_index = i;
            } 
        }
        console.log(max_index + " : " + min_index)
        console.log(`최대값 : ${max}, 최소값 : ${min}`);
        console.log(`최고가 과일 : ${JSON.stringify(fruits[max_index])}`);
        console.log(`최저가 과일 : ${JSON.stringify(fruits[min_index])}`);
 
   </script>
</head>
<body>
    
</body>
</html>
cs

 

 

결과 화면입니다.