Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

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


Giả sử chúng ta có mảng tham chiếu các cụm từ như sau:

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

Cần nối một số phần tử của mảng trên dựa trên mảng khác. Nếu mảng khác là:

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

Kết quả sẽ như:

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

Ở đây, so sánh các phần tử trong cả hai mảng, 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.

Cần viết hàm nhận hai mảng và trả về mảng đã nối mới.

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

Kết quả

Điều này sẽ tạo ra đầu ra sau:

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