Modify an Array Based on Another Array in 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.

Example

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

Output

This will produce the following output −

[ 'your', 'majesty', 'they are', 'ready' ]
Updated on: 2020-11-25T04:57:14+05:30

896 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close