假设我们有一个短语参考数组,如下所示:
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' ]