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

Cartesian Product แบบคั่นด้วยแดชของอาร์เรย์จำนวนใดก็ได้ใน JavaScript


เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าคงที่จำนวนเท่าไรก็ได้ ฟังก์ชันควรคำนวณและคืนค่าอาร์เรย์ของ Cartesian product ของทุกองค์ประกอบจากอาร์เรย์คั่นด้วยแดช (-)

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

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const arr1= [ 'a', 'b', 'c', 'd' ]; const arr2= [ '1', '2', '3' ]; const arr3= [ 'x', 'y' ]; 
const dotCartesian = (...arrs) => { 
  const res = arrs.reduce((acc, val) => { 
    let ret = []; 
    acc.map(obj => { 
      val.map(obj_1 => { 
        ret.push(obj + '-' + obj_1) 
      }); 
    }); 
    return ret; 
  }); 
  return res; 
}; 
console.log(dotCartesian(arr1, arr2, arr3));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

[ 
  'a-1-x', 'a-1-y', 'a-2-x', 
  'a-2-y', 'a-3-x', 'a-3-y', 
  'b-1-x', 'b-1-y', 'b-2-x', 
  'b-2-y', 'b-3-x', 'b-3-y', 
  'c-1-x', 'c-1-y', 'c-2-x', 
  'c-2-y', 'c-3-x', 'c-3-y', 
  'd-1-x', 'd-1-y', 'd-2-x', 
  'd-2-y', 'd-3-x', 'd-3-y' 
]