Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

แก้ไขอาร์เรย์ตามอาร์เรย์อื่น JavaScript


สมมติว่าเรามีอาร์เรย์อ้างอิงของวลีเช่นนี้ -

const reference = ["your", "majesty", "they", "are", "ready"];

และเราจำเป็นต้องรวมองค์ประกอบบางอย่างของอาร์เรย์ด้านบนโดยอิงจากอาร์เรย์อื่น ดังนั้นหากเป็นอาร์เรย์อื่น -

const another = ["your", "they are"];

ผลลัพธ์จะเป็นเช่น −

result = ["your", "majesty", "they are", "ready"];

ในที่นี้ เราเปรียบเทียบองค์ประกอบในอาร์เรย์ทั้งสอง เรารวมองค์ประกอบของอาร์เรย์แรกหากมีอยู่ด้วยกันในอาร์เรย์ที่สอง

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวสองอาร์เรย์และส่งกลับอาร์เรย์ที่เข้าร่วมใหม่

ตัวอย่าง

const reference = ["your", "majesty", "they", "are", "ready"];
const another = ["your", "they are"];
const joinByReference = (reference = [], another = []) => {
   const res = [];
   const filtered = another.filter(a => a.split(" ").length > 1);
   while(filtered.length) {
      let anoWords = filtered.shift();
      let len = anoWords.split(" ").length;
      while(reference.length>len) {
         let refWords = reference.slice(0,len).join(" ");
         if (refWords == anoWords) {
            res.push(refWords);
            reference = reference.slice(len,reference.length);
            break;
         };
         res.push(reference.shift());
      };
   };
   return [...res, ...reference];
};
console.log(joinByReference(reference, another));

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

[ 'your', 'majesty', 'they are', 'ready' ]