코딩기록

이중 배열에서 최대값 찾기 본문

프론트/JS)코딩테스트

이중 배열에서 최대값 찾기

뽀짝코딩 2025. 2. 3. 11:27
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;

 

 

 

 

 

 

반응형
Comments