사전캠프 2주차(6/5) TIL

slppills·2024년 6월 5일

TIL

목록 보기
9/69

코드카타 29번 : 제일 작은 수 제거하기

내 코드 :

function solution(arr) {
    const minValue = Math.min(...arr);
    if (arr.length === 1) {
        return [-1];
    } else {
        for (const a of arr) {
            if (a === minValue) {
                arr.splice(arr.indexOf(a), 1);
                break;
            }
        }
    }
    return arr;
}

Javascript에서 배열의 최댓값, 최솟값 구하기

배열에서 최댓값, 최솟값을 구할 때 구하는 값이 숫자인 경우에는 Javascript의 내장함수인 Math.max()와 Math.min()을 사용하여 구할 수 있다.

  • 문자열의 최댓값, 최솟값을 구하고 싶다면, 배열의 프로퍼티 함수인 reduce 함수를 사용하거나 또는 sort 함수를 사용하여 정렬 후 첫 번째 인덱스와 마지막 인덱스의 값을 구하는 방법도 존재한다.
  • Math.max 함수와 Math.min 함수는 반복문에 비해 코드는 간단하지만, 배열의 요소가 많을 경우 에러가 발생하므로, 배열의 요소가 많지 않은 경우 사용해야 한다.

Math.max() : 숫자의 최대값을 구하는 함수

const maxValue = Math.max(5, 4, 3, 2, 1);

console.log(`maxValue : ${maxValue}`);	// maxValue : 5

- 배열의 요소중 최대값을 구하려면 spread( ... ) 연산자를 사용

const arr = [5, 4, 3, 2, 1];

const maxValue = Math.max(...arr);

console.log(`maxValue : ${maxValue}`);	// maxValue : 5

Math.min() : 숫자의 최소값을 구하는 함수

  • Math.min()도 Math.max랑 사용법은 똑같다.

출처: https://developer-talk.tistory.com/159 [DevStory:티스토리]

0개의 댓글