- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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' ]
Advertisements