Combining elements from one array using the elements of another array

I have two sets of words:

const words = ['a man', 'a man who', "hiding"];

const speechWords = ["this", "is", "a", "man", "hiding", "under", "blanket", "a", "man", "who", "lives", "here"];

My goal is to search for any exact matches (based on word order) from the words array within the speechWords array and create a new combined array like this:

["this", "is", "a man", "hiding", "under", "blanket", "a man who", "lives", "here"]

It's important to note that if a matching phrase from the words array is found, the corresponding elements from speechWords should be joined together.

Please Note: The original order of the speechWords array must remain unchanged.

I attempted to iterate through the words array, splitting the words and then searching each one individually in another loop over the speechWords array, but unfortunately, I did not achieve the desired results...

Answer №1

If we want to transform a long string by replacing spaces with symbols and then inserting specific substrings from an array called words, one approach is as follows:

const words = ['a man', 'a man who', "hiding"];

const speechWords = ["this", "is", "a", "man", "hiding", "under", "blanket", "a", "man", "who", "lives", "here"];

let transformedSpeech = speechWords.join('@');
for (substring of words) {
    transformedSpeech = transformedSpeech.replace(substring.replaceAll(' ', '@'), substring);
}
transformedSpeech = transformedSpeech.split('@');

console.log(transformedSpeech)

Answer №2

When duplicating an array

let originalArray = [3, 6, 9]

let cloneArray = [...originalArray, 12, 15, 18]

console.log(cloneArray) // [3, 6, 9, 12, 15, 18]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript - Toggle Checkbox State Based on Array Values

Currently, I'm in the process of building a Laravel user management system for a project. This system will allow admins to edit any selected user who is registered on our website. Upon clicking the edit button, a modal form containing the user's ...

What is the mechanism for handling click events in AngularJS?

Upon receiving JSON data on my webpage, I want to enable "like" and "dislike" options for buttons with a click event implemented through the code snippet below. However, I am encountering difficulties in achieving the desired outcome and am unsure of how ...

What is the best way to showcase a chart using jquery?

Is there a way to incorporate trendlines or target lines in highcharts similar to fusion chart? I have been able to draw them successfully in fusion charts. Check out this fiddle link: http://jsfiddle.net/Tu57h/139/ I attempted to recreate the same in hi ...

"Creating dynamic movement for a collection of layered images through asynchronous operations in JavaScript: A step

I have a collection of 10 shapes that together form an intricate square image, depicted in the diagram below. My goal is to animate each shape by utilizing the output of a periodic function such as sine, which would dynamically respond to the user's m ...

Performing interpolation in Python without explicitly defining the indices

I am faced with a challenge where I have two arrays, x and y, of the same length. My goal is to determine the value of y corresponding to x=0.56. However, 0.56 is not an exact value in array x. I am seeking a way for Python to automatically identify the c ...

What is the best way to extract only numeric values from an array containing both numbers and letters in C programming?

Just joined this community and seeking some help. I have a text file with the following content: 6 <cr> R 0 R 1 R 4 R 36 R 0 R 4 /modified/ Here's my code snippet. My goal is to read each line into an array, convert that array into an integer, ...

Steering your way to accessing a JSON object in JavaScript

Is there a way to access the JSON object in javascript when the JSON object is structured like this? {'':'my-first-Name'} I am facing difficulty accessing the property with an empty name. Any suggestions on how to resolve this issue w ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

Highlighting PHP files as JavaScript files in Sublime Text for improved readability

I'm working with a group of .php files in Sublime Text that primarily consist of JavaScript code with some PHP constants mixed in. Is there a way to configure Sublime Text to consistently highlight these files as JavaScript instead of PHP without havi ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task. Our standard approach ...

The useQuery Hook displaying loading state without being invoked

I'm having some trouble setting up a search bar for my new project. It seems like I might have made some mistakes along the way. Currently, the book state is set to null and the useQuery hook is utilizing it to search for books. However, I only want ...

What is the best way to ensure that the search box automatically adjusts its position and size regardless of the screen resolution?

I'm currently working on a responsive website project and facing an issue with the absolute positioning of the search bar on the main page, which is crucial for me. Below is the code snippet: <div class="span4"> <form class="well form ...

Get the value associated with a specific key in an array

Thanks to the discord API, I successfully created a table that maps different role identifiers to different keys. However, I am facing a challenge in displaying a text based on the selected identifier using a condition. I tried using the json_decode functi ...

This function does not have the capability to save cookies

I am attempting to create and retrieve a cookie using JavaScript. Despite running the code below in Google Chrome, the cookie does not persist after page reload. Here is my code: <html> <title> Cookies </title> <b ...

The concept of reducing functions in JavaScript and the significance of extra brackets

My function looks like this: function ross(array) { return array.map(function(data) { return data.reduce(function(obj, item) { obj[item[0]] = item[1]; return obj; }, {}); }); } ross(array); This code is responsible for converting a ...

What obstacles prevented the implementation of arrays of generics in Java?

Discussion on Java Type Erasure One interesting aspect of Java is its use of type erasure. When you declare new ArrayList<String>(), it actually gets converted into a raw type behind the scenes. Despite this conversion, Java still manages to make it ...

Having trouble with jQuery scrollTop not working after loading content with ajax?

When the html content is loaded via ajax, I need to scroll to a specific element. This element has the attribute data-event-id="". However, there are instances when the variable $('.timelineToolPanel[data-event-id="'+id+'"]').offset().t ...

PHP script to iterate through multiple directories using DirectoryIterator

Looking to update my PHP code to read PDF files from three different paths: pdf_folder/2020/, pdf_folder/2021/, and pdf_folder/2022/. The current code reads just from pdf_folder/2020/ and sends the data to the database. This is the existing code: <?php ...