根據另一個數組修改陣列 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' ]
廣告