Modify an array based on another array JavaScript

Suppose, we have a reference array of phrases like this −

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

And we are required to join some of the elements of above array based on another array so if another array is this −

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

The result would be like −

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

Here, we compared the elements in both the arrays, we joined the elements of the first array if they existed together in the second array.

We are required to write a JavaScript function that takes in two such arrays and returns a new joined array.


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) {
            reference = reference.slice(len,reference.length);
   return [...res, ...reference];
console.log(joinByReference(reference, another));


This will produce the following output −

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