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

วิธีหาส่วนตัดของอาร์เรย์หลายมิติด้วย JavaScript


เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์หลายมิติของอาร์เรย์ค่าคงเขา ฟังก์ชันควรคืนค่าอาร์เรย์ส่วนตัดของทุกซับอาร์เรย์ที่อยู่ในอินพุตอาร์เรย์

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

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

const arr = [ 
  ["garden","canons","philips","universal"], 
  ["universal","ola","uber","bangalore"] 
]; 
const findMultiIntersection = (arr = []) => { 
  const res = []; 
  arr.forEach(el => { 
    const thisObj = this; 
    el.forEach(element => { 
      if(!thisObj[element]){ 
        thisObj[element] = true; 
      } 
      else{ 
        res.push(element) 
      }; 
    }); 
  }, {}); 
  return res; 
}; 
console.log(findMultiIntersection(arr));

ผลลัพธ์

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

[ 'universal' ]