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' ]