Computer >> Máy Tính >  >> Lập trình >> Javascript

Sửa đổi một mảng dựa trên JavaScript mảng khác

Giả sử, chúng ta có một mảng tham chiếu gồm các cụm từ như thế này -

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

Và chúng ta bắt buộc phải nối một số phần tử của mảng trên dựa trên một mảng khác, vì vậy nếu mảng khác thì đây -

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

Kết quả sẽ như thế nào -

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

Ở đây, chúng tôi so sánh các phần tử trong cả hai mảng, chúng tôi nối các phần tử của mảng đầu tiên nếu chúng tồn tại cùng nhau trong mảng thứ hai.

Chúng tôi được yêu cầu viết một hàm JavaScript nhận vào hai mảng như vậy và trả về một mảng mới được kết hợp.

Ví dụ

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));

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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