Combining all string elements in an array while preserving objects - here's how to do it

As I ponder the complexity of my question, I find myself wondering how to condense an array by merging adjacent strings while keeping objects intact. For example:

array = ["I","want","to",[Obj],"come","together"]

The desired output would be:

["I want to", [Obj], "come together"];

I have a hunch that array.reduce() could be the solution, but I still need to fully grasp how that function works.

Answer №1

Combine strings in an array or push non-strings to a new accumulator:

const array = ["I","want","to",[{}],"come","together"]

const isString = s => typeof s === 'string'

const result = array.reduce((r, o) => {
  if(isString(o) && isString(r[r.length - 1])) {
    r[r.length - 1] = `${r[r.length - 1]} ${o}`
  } else {
    r.push(o)
  }

  return r
}, []) 

console.log(result)

Answer №2

Here is a snippet of code that showcases how to manipulate an array in JavaScript:

const array = ["I","want","to",{},"come","together"];

let outputArr = [];
let strArr = [];

array.forEach(elem => {
  if (typeof elem === 'string') {
    return strArr.push(elem);
  }
  
  outputArr.push(strArr.join(' '));
  strArr = [];
  outputArr.push(elem);
});

outputArr.push(strArr.join(' '));

console.log(outputArr);

Answer №3

If you're in the mood for sticking with the good old for-loop :)

var result = [], array = ["I","want","to",{a: 1, b:2},"come","together"];
var i=0;var str = "";
for(; i< array.length; i++){
  if(typeof array[i] === 'object' ){
     result.push(str);
     result.push(array[i]);
     str="";
     
   }else{
    str = str+" "+ array[i];
  }
}
if(i==array.length){
  result.push(str);
}
console.log(result);

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

Guide to making a dropdown menu that pulls information from a text box and displays the location within the text

I'm currently working on a unique dropdown feature that functions like a regular text field, displaying the text position. To achieve this, I've constructed a hidden dropdown menu positioned beneath the text field. My goal is to develop a jQuery ...

What are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Executing scripts within various node project directories using npm

Creating Concurrent NPM Scripts In my main project, I have several node projects nested as subdirectories. Each of these projects has its own node_modules directories and package.json files. My goal is to define an npm script in the main project's pa ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...

What causes the discrepancy in the output of `document.documentElement.childNodes` in JavaScript?

While working on my code exercise today, I came across a special case regarding the "document.documentElement.childNodes" property. Originally, I believed it to represent all child nodes within a tag as before. However, when implementing my code, I noticed ...

Encountering a peculiar error while attempting to install firebase-tools

Currently in the process of deploying my application on Firebase by following a tutorial. I encountered an issue after executing the command npm install -g firebase-tools: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" d ...

Utilizing NPM packages within Grunt-powered workflows

When working with Node, the module loading system is quite straightforward using the require() method to load modules from various locations in the root folder. For example: var qr = require('qr-image'); However, I have been attempting to achi ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

Utilizing JQuery for a Secure LogIn System

Just 3 days ago, my code was running smoothly. But now it seems to have hit a roadblock. Being new to JQuery, I would greatly appreciate if someone could help me pinpoint my mistake. Upon debugging, I noticed that the debugger is not entering the success ...

Tips for choosing a section of a complex vector in Matlab

I have a query that may seem trivial, but I am looking for a way to extract a section of a complex array for visualization in Matlab. Here is an example of what I have tried: n = 100; t = linspace(-1,1,n); x = rand(n,1)+1j*rand(n,1); plot(t(45):t(55),re ...

Enable the ability for anchor links to be clickable when the CSS media print format is used to generate

To illustrate: <a href="https://www.google.com">Google anchor link</a> on the website, it displays as: Google anchor link When printed, it shows as: Google anchor link(https://www.google.com) To address this issue, I included in the CSS: ...

The issue with the dynamic form lies in the malfunctioning of the jquery post() method

Currently, I am in the process of developing a dynamic form generated from a database. I have created a simple form as a test and it seems to be functioning well. However, I have noticed that upon submitting the form for a second time, it retains the previ ...

Ensure that the Promise is resolved upon the event firing, without the need for multiple event

I'm currently working on a solution where I need to handle promise resolution when an EventEmitter event occurs. In the function containing this logic, an argument is passed and added to a stack. Later, items are processed from the stack with differe ...

What is the best way to place a background image at the top left and bottom right corners of an HTML element?

I have a paragraph and I would like to visually mark the beginning and end of the paragraph for the user. I have successfully displayed a background image in the upper left corner, but I am unsure how to position the background image in the lower right co ...

How can I utilize JavaScript to retrieve the background color of a table cell upon clicking?

I am trying to create a function where an alert pops up displaying the background color of a table cell whenever it is clicked. Unfortunately, I am having trouble accessing and retrieving the background color value. The table cell in question is defined a ...

Once it hits the fourth tab, it must not cycle back to the first one

Hi there, I'm new to JavaScript I noticed that when I click the left and right arrows, the tabs circle back to the beginning However, I would like the circle to stop. When it reaches the fourth tab, it should not go back to the first. This should also ...

What are your thoughts on using a click function within the same tag as an ngFor directive in Angular and JavaScript?

There is a table with a row element called tr. Should the `Click` event use the same tag as the `*ngFor` directive? If this is not recommended, how can I enhance the code? ...

In Node.js and Postgresql, encountering the error "Trying to access a property that is undefined" is common and can be frustrating

const pool = new pg.Pool(config); var tablename = req.body.tablename; pool.connect(function (err, client, done) { var query_get_value = 'SELECT * FROM '+ tablename; client.query(query_get_value, function (err, result) { d ...

JavaScript and jQuery code: Trigger the vjs-fade-out class to toggle when the userActive value in video.js changes

I am currently utilizing video.js to develop a player that is compatible with various devices. One crucial feature I have included is a custom "return to menu" button located in the top right corner of the video player. The challenge I am facing is dynamic ...

Exploring the relationship between MongoDB and Node.js: Retrieving a document based on its _id using a UUID (GUID

As I work on creating a restAPI with node.js, I am facing an issue while querying a mongo collection. While I can successfully query using strings such as "companyname", I struggle when it comes to querying the "_id" element in the document. In my mongo d ...