Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 시퀄 문법
- 배엘에서 스왑
- 깃 토큰 만료
- @Moditying @Query
- 우분투 시간 변경
- 중복된 단어
- 중복 문자열
- 중첩배열평탄화
- ...점점점문법
- ubuntu타임존
- sql like연산자
- 재귀스왑
- 중복문자제거
- lastIndexOf()
- 코딩 어?
- 객체의 밸류값만 찾기
- 프론트엔드 스쿨
- 단어 제거
- 중첩배열
- 스프링 데이타 JPA
- 중복단어제거
- indexOf()
- 문자열순서바꾸기
- 레디스 확인
- sql 문자열 패턴 검색
- 객체의키값만 찾기
- 5.3.8 Modifying Queries
- js 문자열을 문자배열로
- 문자열 중복
- 제로베이스
Archives
- Today
- Total
코딩기록
이중 배열에서 최대값 찾기 본문
728x90
이중 배열에서 최대값만 찾아 일차원 배열로 만들기
const twoArr = [[1, 2], [3, 4], [5, 6]];
const maxValues = twoArr.map(subArr =>
subArr.reduce((max, num) => Math.max(max, num), -Infinity));
console.log(maxValues); // [2, 4, 6]
최대값만 더하기
.reduce를 추가한다.
const twoArr = [[1, 2], [3, 4], [5, 6]];
const sumOfMaxValues = twoArr.map(subArr =>
subArr.reduce((max, num) => Math.max(max, num), -Infinity))
.reduce((sum, maxVal) => sum + maxVal, 0);
console.log(sumOfMaxValues); // 12
빈 배열 처리하는 코드 추가
const twoArr = [[1, 2], [], [5, 6]];
const maxValues = twoArr.map(subArr =>
subArr.length ? Math.max(...subArr) : 0 // 빈 배열이면 기본값 0 반환 혹은 -Infinity
);
console.log(maxValues); // [2, 0, 6]
빈 배열이면 0을 반환하여 합산할 때 0으로 처리.
최대값만 더하기
const twoArr1 = [[1, 2], [], [5, 6]];
const max = twoArr1.map(subArr =>
subArr.length ? Math.max(...subArr) : -Infinity // 빈 배열이면 기본값 -Infinity 반환
);
console.log(max); // [2, -Infinity, 6]
const total = max.reduce((acc, cur) => acc + (cur === -Infinity ? 0 : cur), 0); // -Infinity는 0으로 처리
console.log('total: ', total); // 8
return total;
반응형
'프론트 > JS)코딩테스트' 카테고리의 다른 글
이중 배열을 일차원 배열 하나로, 일차원 배열로 구분 (0) | 2025.02.03 |
---|---|
코테) 맞팔 관계인 쌍의 수 리턴 (0) | 2025.01.17 |
JS) 객체배열에서 배열 없애기 [ {}, {} ] => {}, {} (0) | 2025.01.07 |
set) 중복된 문자 제거 / [...new Set(매개변수)].join(''); set으로 중복 제거 / 중복 단어 제거 (0) | 2024.09.25 |
replace) 옹알이 (1) / 문자배열과 동일한 문자 카운트, 개수 구하기 - forEach + 유효성검사, filter, .length (0) | 2024.09.25 |
Comments