Modify an array based on another array JavaScript

When working with arrays in JavaScript, you might need to modify one array based on patterns or elements found in another array. This article demonstrates how to join consecutive elements from a reference array when they appear as combined phrases in a second array.

Problem Statement

Suppose we have a reference array of individual words:

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

And we want to modify it based on another array that contains some words joined together:

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

The goal is to create a new array where consecutive elements from the reference array are joined if they appear as a single phrase in the second array:

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

Notice how "they" and "are" from the reference array were combined into "they are" because this phrase exists in the second array.

Solution Implementation

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

const joinByReference = (reference = [], another = []) => {
    const res = [];
    const refCopy = [...reference]; // Create a copy to avoid mutating original
    const filtered = another.filter(a => a.split(" ").length > 1);
    
    while(filtered.length) {
        let anoWords = filtered.shift();
        let len = anoWords.split(" ").length;
        
        while(refCopy.length >= len) {
            let refWords = refCopy.slice(0, len).join(" ");
            if (refWords == anoWords) {
                res.push(refWords);
                refCopy.splice(0, len); // Remove matched elements
                break;
            }
            res.push(refCopy.shift());
        }
    }
    return [...res, ...refCopy];
};

console.log(joinByReference(reference, another));
[ 'your', 'majesty', 'they are', 'ready' ]

How It Works

The algorithm follows these steps:

  • Filter phrases: Extract only multi-word phrases from the second array
  • Pattern matching: Check if consecutive words in the reference array match any phrase
  • Join or keep separate: If a match is found, join the words; otherwise, keep them as individual elements
  • Continue processing: Repeat until all elements are processed

Example with Multiple Phrases

const reference2 = ["hello", "world", "how", "are", "you", "today"];
const another2 = ["hello world", "are you"];

const result2 = joinByReference(reference2, another2);
console.log(result2);
[ 'hello world', 'how', 'are you', 'today' ]

Key Points

  • The function creates a copy of the reference array to avoid mutating the original
  • Only multi-word phrases from the second array are considered for joining
  • The algorithm processes phrases in order and matches consecutive elements
  • Unmatched elements remain as individual items in the result

Conclusion

This approach efficiently modifies an array by joining consecutive elements based on patterns found in another array. It's useful for text processing, data transformation, and array manipulation tasks where you need to group related elements dynamically.

Updated on: 2026-03-15T23:19:00+05:30

998 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements