Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 2D 배열을 희소 배열로 변환

<시간/>

다음과 같은 2차원 배열이 있다고 가정해 보겠습니다. -

const arr = [
   [3, 1],
   [2, 12],
   [3, 3]
];

이러한 배열을 취하는 JavaScript 함수를 작성해야 합니다.

그런 다음 함수는 입력 배열에 있는 요소의 인덱스를 제외하고 정의되지 않은 것으로 초기화된 모든 요소를 ​​포함하는 새로운 2차원 배열을 만들어야 합니다.

따라서 입력 배열의 경우

output[3][1] = 1;
output[2][12] = 1;
output[3][3] = 1;

나머지 모든 요소는 정의되지 않은 상태로 초기화되어야 합니다.

따라서 최종 출력은 다음과 같아야 합니다. -

const output = [
   undefined,
   undefined,
   [
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      1
   ],
   [
      undefined,
      1,
      undefined,
      1
   ]
];

예시

이에 대한 코드는 -

const arr = [
   [3, 1],
   [2, 12],
   [3, 3]
];
const map2D = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      res[el[0]] = res[el[0]] || [];
      res[el[0]][el[1]] = 1;
   });
   return res;
};
console.log(map2D(arr));

출력

콘솔의 출력은 -

[
   <2 empty items>,
   [ <12 empty items>, 1 ],
   [ <1 empty item>, 1, <1 empty item>, 1 ]
]