개발 기술/개발 이야기

이중배열(2d array)에서 최고, 최저값 찾기

by GicoMomg (Lux) 2022. 1. 2.

🤖 이번 시간에는 이중 배열의 특정 인덱스별 최고, 최저값을 구해보자

1. 시작하기

1) 이중 배열 형태

  • 이번 코끼리반의 중간고사 시험 결과는 아래와 같다.
const scores = [[100, 70],[87, 50],[45, 70],[60, 77],[55, 27]];
순서 과목1 과목2
1 100 70
2 87 50
3 45 70
4 60 77
5 55 27
  • 그리고 내일까지 코끼리반 선생님은 각 과목별 최고, 최저점수를 산출해야하는데,
  • 이중 배열에서 각 과목별(index별) 최고&최저점수는 어떻게 구할 수 있을까? 한 번 알아보자



2) 전체 코드보기

🤖 getMinMax2DArr()는 첫 번째 인자로 arr, 두 번째 인자로 idx를 받아 idx별 최고, 최저값을 리턴한다.

function getMinMax2DArr(arr, idx) {
  const min = Math.min.apply(null, arr.map((el) => el[idx]));
  const max = Math.max.apply(null, arr.map((el) => el[idx]));
  return `max value is ${max}, min value is ${min}`;
}



3) 코드 상세히보기

[1] 특정 인덱스의 값 접근하기, map()

function getMinMax2DArr(arr, idx) {
  const min = Math.min.apply(null, arr.map((el) => el[idx]));  //[1] map 함수
  const max = Math.max.apply(null, arr.map((el) => el[idx]));  //[1] map 함수
  return `max value is ${max}, min value is ${min}`;
}

  • 우리는 이중 배열에서 특정 인덱스에 해당하는 원소들이 필요하다.
  • map()은 배열 요소에 대해 함수를 실행한 결과를 가지고 새로운 배열을 만들어준다.
  • 이중 배열에서 index = 1인 요소만 모으고 싶다면 아래와 같이 사용할 수 있다.
const scores = [[100, 70],[87, 50],[45, 70],[60, 77],[55, 27]];

const idxOneValues = arr.map((el) => el[1]);
console.log(idxOneValues);    


[2] 최고, 최저값 구하기, Math.min(), Math.max()

function getMinMax2DArr(arr, idx) {
  const min = Math.min.apply(null, arr.map((el) => el[idx]));  //[2] Math.min
  const max = Math.max.apply(null, arr.map((el) => el[idx]));  //[2] Math.max
  return `max value is ${max}, min value is ${min}`;
}

  • 우리는 최고, 최저값을 구할 때 Math.min, Math.max를 사용할 수 있다.
console.log(Math.min(5,2,3,4,10)); // 2
console.log(Math.max(5,2,3,4,10)); // 10

  • 하지만 두 함수는 숫자를 인자로 받으며, 배열을 사용할 수 없는 단점이 있다.
  • 만약 배열 원소의 최고, 최저값을 구하려면 spread(...array) 연산자를 사용해야 한다.
console.log(Math.max([5,2,3,4,10]));    // NaN
console.log(Math.max(...[5,2,3,4,10])); // 10

🤔 min, max에서 array를 spread연산으로 사용할 수 있다면 함수에서 apply를 안써도 되지 않나?

  • 만약 apply 대신 spread연산자만 사용하면 함수는 아래와 같이 수정할 수 있다.
function getMinMax2DArr(arr, idx) {
  const min = Math.min(...arr.map((element) => element[idx])); // spread연산자 사용
  const max = Math.max(...arr.map((element) => element[idx])); // spread연산자 사용
  return `max value is ${max}, min value is ${min}`;
}
  • 하지만, apply를 쓰게 되면 array인자로 받을 수 있기에 spread 보다 로직이 간단해진다.

[3] 배열을 인자로 받을 수 있게, apply()

function getMinMax2DArr(arr, idx) {
  const min = Math.min.apply(null, arr.map((el) => el[idx]));  //[3] apply
  const max = Math.max.apply(null, arr.map((el) => el[idx]));  //[3] apply
  return `max value is ${max}, min value is ${min}`;
}
  • apply(this대상, 인자)는 함수의 this를 특정 객체로 변경할 수 있으며, 배열을 인자로 지정할 수 있다.
  • (apply에 대한 자세한 설명은 이 링크에서 확인할 수 있다.)
  • min, max의 경우, this로 지정할 객체가 없으므로 null로 지정하고, 두 번째 인자로 배열을 넣어주자.
function getMinMax2DArr(arr, idx) {
  const min = Math.min.apply(null, arr.map((el) => el[idx])); 
  // Math.min.apply(null, 배열) 형태
  ...
}



반응형

댓글