Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หา Transpose ของอาร์เรย์ 2 มิติใน JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ 2 มิติและคืนค่าอาร์เรย์ transpose ของมัน

โค้ดสำหรับเรื่องนี้จะเป็น:

วิธี 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 ] ]