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

การจัดเรียงในอาร์เรย์หลายมิติใน JavaScript


ภาพรวม

สมมติว่าเรามีอาร์เรย์ของอาร์เรย์:

const arr = [
  ["A","F","A","H","F","F"],
  ["F","A","A","F","F","H"]
];

เราต้องเขียนฟังก์ชันจัดเรียงอาร์เรย์ย่อยทั้งหมดภายในตามกฎ:

  • อิลิเมนต์ที่ไม่ใช่ "A" หรือ "F" คงตำแหน่งเดิม
  • อิลิเมนต์ที่เป็น "A" หรือ "F" ให้จัดเรียงตามตัวอักษร

ผลลัพธ์ที่คาดหวัง

const output = [
  ["A","A","A","H","A","F"],
  ["F","F","F","F","F","H"]
];

หมายเหตุ: อิลิเมนต์อาจเปลี่ยนอาร์เรย์ย่อยได้หากอัลกอริทึมจัดเรียงทำให้เป็นเช่นนั้น

ตัวอย่างโค้ด

const arr = [
  ["A","F","A","H","F","F"],
  ["F","A","A","F","F","H"]
];

const customSort = (arr = []) => {
  const order = [].concat(...arr.slice()),
  res = [];
  order.forEach((el, ind) => {
    if (el === 'A') {
      const fIndex = order.indexOf('F');
      if (fIndex < ind) {
        order[fIndex] = 'A';
        order[ind] = 'F';
      }
    }
  });
  arr.forEach(el => res.push(order.splice(0, el.length)));
  return res;
};

console.log(customSort(arr));

ผลลัพธ์ในคอนโซล

[ [ 'A', 'A', 'A', 'H', 'A', 'F' ], [ 'F', 'F', 'F', 'F', 'F', 'H' ] ]