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

2차원 배열의 전치 찾기 JavaScript

<시간/>

우리는 2차원 배열을 가져와서 전치된 배열을 반환하는 JavaScript 함수를 작성해야 합니다.

이에 대한 코드는 -

방법 1:Array.prototype.forEach() 사용

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

const transpose = arr => {
   const res = [];
   arr.forEach((el, ind) => {
      el.forEach((elm, index) => {
         res[index] = res[index] || [];
         res[index][ind] = elm;

      });
   });
   return res;
};
console.log(transpose(arr));

방법 2:Array.prototype.reduce() 사용

const arr = [
   [0, 1],
   [2, 3],
   [4, 5]
];
const transpose = arr => {

   let res = [];
   res = arr.reduce((acc, val, ind) => {
      val.forEach((el, index) => {

         acc[index] = acc[index] || [];
         acc[index][ind] = el;

      });
      return acc;
   }, [])
   return res;
};

console.log(transpose(arr));

두 방법 모두에 대한 콘솔의 출력은 다음과 같습니다. -

[ [ 0, 2, 4 ], [ 1, 3, 5 ] ]