Merging consecutive values within an array of objects using JavaScript

When combining consecutive tags, my goal is to merge the text if the tags are the same.

Therefore, with the following input, the desired output should be:


Speaker-2:Do you want the systems in English or en espanol
Speaker-1:Heinous Spaniel
Speaker-2:For English press one for Spanish press 2 in Espanol
Speaker-1:Choirs a horror Janeiro at e ends in the pro gun to sober Tuesday to enter but I will have email but if you a new window
Speaker-2:but I put one that's 1 or 2.0 press he only those

 

   const note = [
    {
        text: 'do you want the systems in English or en espanol',
        tag: 2,
    },
    {
        text: 'heinous Spaniel',
        tag: 1,
    },
    {
        text: ' for English press one for Spanish press 2',
        tag: 2,
    },
    {
        text: ' in Espanol',
        tag: 2,
    },
    {
        text: ' choirs a horror Janeiro at e ends in the pro gun to sober Tuesday to enter',
        tag: 1,
    },
    {
        text: ' but I will have email but if you a new window',
        tag: 1,
    },
    {
        text: " but I put one that's 1 or 2.0 press he only those",
        tag: 2,
    },
];

const ip = note
    .map((e, i) => {
        const chanel = e.tag;
        let te = e.text.trim();
        const next = note[i - 1] ? note[i - 1].tag : 0;
        if (chanel === next) {
            te = `${note[i - 1].text.trim()} ${te}`;
            note[i - 1].text = te;
            note.splice(i, 1);
        }
        return {
            [`Speaker-${chanel}`]: te.charAt(0).toUpperCase() + te.slice(1),
        };
    })
    .filter(e => !!e);
let strimged = JSON.stringify(ip)
    .replace(/[{}"]/g, '')
    .split(',')
    .join('\n');
strimged = strimged.substring(1, strimged.length - 1);
console.log(strimged);

Answer №1

The solution lies in using Array.reduce() method.

const messages = [
    {
        text: 'do you want the systems in English or en espanol',
        tag: 2,
    },
    {
        text: 'heinous Spaniel',
        tag: 1,
    },
    {
        text: ' for English press one for Spanish press 2',
        tag: 2,
    },
    {
        text: ' in Espanol',
        tag: 2,
    },
    {
        text: ' choirs a horror Janeiro at e ends in the pro gun to sober Tuesday to enter',
        tag: 1,
    },
    {
        text: ' but I will have email but if you a new window',
        tag: 1,
    },
    {
        text: " but I put one that's 1 or 2.0 press he only those",
        tag: 2,
    },
];

 let previousTag = 0;

let formattedMessages = messages.reduce((output, msg) => {

  if(msg.tag === previousTag) {
    output += msg.text;
  } else {
    output += `\nSpeaker-${msg.tag}: ` + msg.text;
    previousTag = msg.tag;
  } 
  return output;
}, '');

console.log(formattedMessages);

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

Converting human-readable dates into a Date object

How can I reliably convert human-entered dates into a Date() object for my project that utilizes a ML text extractor? Although seemingly straightforward, the issue lies in the wide variety of formats used by individuals when entering dates, ranging from " ...

Detonating the second-level element in a PHP/Typescript array

My PHP code is currently formatting an array for me with the following structure: $data = $dataQuery->fetchAll(PDO::FETCH_ASSOC); if(count($data)){ $data_arr=array(); $data_arr["records"]=array(); $data_arr["records"] = ...

Activate datepicker upon choosing a symbol

If the symbol field is selected, the datepicker is enabled. If the symbol field is not selected, the datepicker remains disabled. <script src="{{asset('js/libs/jquery.js')}}" crossorigin="anonymous"></script> <link href="https:/ ...

Utilize JSON data as a source for autocomplete in JQuery

I have encountered an issue while using the autocomplete widget of JQuery with JSON to parse database information. Despite searching for a solution, I have not been able to resolve it. Here is my PHP file with JSON parsing: The error displayed in the brow ...

When transitioning from one screen to another in React Native, the toast does not appear. Setting a setTimeout of 1000 fixes this issue temporarily, but I am looking for a way to display

visitSite("openshift") setTimeout(() => { displayMessage('Shift Assigned', 'success'); }, 1000); // HOWEVER, I prefer to have the functionality of displaying a success message and navigating between screens separated into distin ...

Display the quantity of elements in an array that has been sorted using ngRepeat

Currently, I am building a portfolio website and I want the index page to display only the most recent five items added to the portfolio. However, as someone who is still learning AngularJS and its ordering abilities, I am facing some challenges. Here is w ...

Is there a way for me to prevent the need to open a new window to view the results?

Can someone help me with my code? I want to display results without opening a new window or replacing the current content in the same window. I'm thinking of using AJAX to show results in a dialog window using JQueryUI but I'm not sure how to do ...

Is it possible for Nuxtjs/apollo to make apollo wait for other requests before initiating the query?

Is there a way to have Apollo wait for the result of one request to a third party before making either of two queries? Or should I manually add the appropriate query to Apollo after receiving the results? ...

Using Strapi and Next.js to retrieve user information

After searching for similar questions with no luck, I'm reaching out for help. Building an authentication system using Strapi and Next.js, I'm faced with a task that seems simple but eludes me. The main question is: How can the client retrieve u ...

Exploring the integration of API with Dropdown list in Flutter

Functional Output with Flutter Dropdown Hey fellow Flutter/Dart developers, I'm just starting out with Flutter. The code snippet below demonstrates a working dropdown without API integration, but I'm looking to populate the dropdown list with dat ...

Encountering issues with IEnumerable in a view that contains a JSON object

After successfully serializing a JSON string in a previous question, I have encountered difficulty displaying the results on the view. Despite fixing the model and controller, it seems that the issue lies within the view itself. The error message I am curr ...

Can you explain the variance between Selenium and WebDriver's seleniumProtocol as it pertains to DefaultNode.json?

While setting up Selenium Grid 2, I came across a sample json configuration file from this link. My test scripts are in C# and utilize Selenium WebDriver. I am currently exploring the distinctions between these two protocols and determining which one is ...

Questions about clarifying JS promises and async-await functions

After doing some reading on promises in JavaScript, I have come across conflicting information which has left me with a few basic questions. I have two specific questions that need clarification: Is it necessary for every function in JavaScript to be ca ...

Tips for feeding information into AWS Kinesis using Particle cloud JSON web hooks

Seeking advice or insights on how to transmit a JSON payload for data ingestion into AWS Kinesis. Currently utilizing Ubidots for data visualization, but looking to switch to AWS QuickSights for analysis and visualization purposes. Below is an example of a ...

Creating a Yo Meanjs project seems like an insurmountable challenge

As I embark on this online tutorial journey, I encountered an issue. All the necessary installations and preparations have been completed, but when instructed to run 'yo meanjs', an error message appeared: https://i.sstatic.net/0dCB4.png Could ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Exploring the Depths of GraphQL Mutations: Nesting for

Currently seeking examples of writing nested mutations. Specifically, I am creating a mutation for a recipe object with the following schema: const RecipeType = new GraphQLObjectType({ name: "Recipe", fields: () => ({ id: { type: GraphQLID }, ...

Changing the time zone of a UTC date string while preserving the original format

Is there a way to convert a UTC date string to the current user's timezone while keeping the original date string format intact? Take for example the following code snippet that accomplishes this: var data = '2017-04-24 12:06:37'; var date ...

Is it possible to use both the filter $select.search and the limitTo $select.infiniteCurrentLimit on a single ui-select field?

I am facing a challenge with my ui-select field which utilizes infinite-scroll functionality due to having a large number of options. However, it becomes cumbersome to scroll down and find the desired option among so many choices. <ui-select-choices ...

Unable to access res.json within a callback function

Currently, I am developing an API endpoint where I utilize the /authenticate route to handle data submissions. When data is posted to this endpoint, I employ the plaidClient.getAuthUser function to retrieve the user's account details. Subsequently, my ...