Explore the elements within an array and combine them into a single string using JavaScript ES6

I am currently working on processing an array of objects that represent authors. My goal is to map through these objects and concatenate their names with some formatting applied. However, I seem to be encountering a challenge with this seemingly simple task.

const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
let names = authors.map( (a, i) => {
  return `${a.name} is cool`
})
console.log(names)
// ["Steven is cool","Nick is cool"]
// while my desired output is "Steven is cool Nick is cool"

Is there a way for me to achieve the desired string format by mapping through the objects?

For instance, instead of getting individual strings like "Steven is cool" and "Nick is cool", I aim to generate a single concatenated string like "Steven is cool Nick is cool".

Answer №1

Try using the Array#Join method:

authors.map((a) => `${a.name} is awesome`).join(' ');

See it in action here!


Please note: The join method predates ES6, so it's not a new feature.

Answer №2

I personally find the utilization of reduce to be preferable

Older ES5 version

authors.reduce(function (result, individual) { 
  return (result + ' ' + individual.name + ' is cool');
}, ''); 

Newer ES6 version

authors.reduce((result, individual) => `${result} ${individual.name} is cool`, '');

Answer №3

Here's a different approach that eliminates the need for mapping and joining - you can simply reduce instead.

const writers = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]

console.log(writers.reduce( (prev,current) => `${prev} ${current.name} is awesome `, ""))

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

What is the best way to asynchronously load an external javascript file in a popup.html file?

I have successfully implemented all the necessary functionalities, but I noticed a delay in loading the popup.html after adding an external javascript file. This file is only a few lines long, so the delay is quite frustrating. To eliminate this lag, I be ...

Embracing the Quirks of JSON: A Call for a

Currently, I am in the process of developing a webpage that involves incorporating four distinct JSON entities (objects, arrays). Excuse my lack of appropriate jargon. Upon receiving the JSON data, it is structured as an object with numerous sub-objects, ...

What is the method for activating a resume using sound settings with JavaScript?

Having trouble controlling the audio with this code. When I click a button that has an onclick calling playpause(), it pauses the audio. But when I click again, it doesn't resume. var audio=new Audio("music.mp3"); function music() { a ...

Internet Explorer automatically moves the cursor to the beginning of a textarea when it gains

When trying to insert "- " into an empty textarea, I am facing issues with Internet Explorer. While Firefox and Chrome work perfectly fine by inserting the text as expected, IE causes it to jump to the beginning of the textarea after insertion. Therefore, ...

The success function is not functioning properly with the validation engine

I'm having trouble getting this script to function properly as it keeps showing errors whenever I try to run it. $(document).ready(function() { $("#form1").validationEngine({ ajaxSubmit: true, ajaxSubmitFile: "note/note.php", ...

Incorporating JSON data into a MySQL database

I have a large array that I need to insert into a mysql database. The array has been converted to json code... How can I efficiently add this json array to mysql? $fields=json_encode($_POST['fields']); $sql="INSERT INTO forms (name, recipient, f ...

Contrast between a character array and a string defined by a pointer

While studying pointers in the K&R book, I came across an interesting distinction between two definitions: char amessage[] = "now is the time"; /* this is an array */ char *pmessage = "now is the time"; /* this is a pointer */ ...

Ways to ensure the INPUT element occupies the full TD cell of a table

Using the following table as a reference: <table> <tbody> <tr> <td> <input value = "this is the text"> </td> </tr> </tbody> </table> I am facing an issue where the &l ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Remove any objects with nil values from an array using filter and flatMap in Swift 4

I am populating a UICollectionView with results retrieved from a query. Occasionally, the records returned do not contain images. I want to exclude these objects completely. How can I avoid displaying results from a JSON query that do not include any imag ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Delete Refresh Support Jquery

I am attempting to have the div recentactivity only refresh when the Remove button is clicked < a href='#' onclick=\"javascript:remove_wall('$id')\">Remove However, every time I click on the link, it keeps trying to re ...

JQuery - Real-time computation and transformation within an interactive spreadsheet

I have a dynamic HTML table where rows can be added, and I am looking to read the value in Liters and convert it to US Gallons as the user enters the values. I want to take the input in Liters, convert it, and display it in the USG input field. View Dynam ...

Error: The object prototype can only be an Object or null, not undefined

During development, my app runs smoothly. However, when I build the project for production using "npm run build," I encounter the following error: 2.9b72e8af.chunk.js:sourcemap:1 Uncaught TypeError: Object prototype may only be an Object or null: undefin ...

Issue with Inline JavaScript in `href` tag not functioning correctly in Firefox

I am encountering an issue with this inline JavaScript not working in Firefox. I need to figure out how to make it function correctly in Firefox. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style> ...

Guide on organizing data by the final character in a column

For my assignment, I need to create a line plot based on the last letters of values in one column. Here is an example: data <- data.frame(c('apple', 'banana', 'pie', 'fries', 'tomato', 'cheese' ...

Is it necessary to have both Express and express-generator in my toolbox?

Recently delving into the world of node.js and stumbled upon express; While browsing the npm repository site https://www.npmjs.com/package/express, I noticed that the installation process is clearly stated as: $ npm install express However, further down ...

How can I replicate the function of closing a tab or instance in a web browser using Protractor/Selenium?

I want to create an automated scenario where a User is prompted with an alert message when they try to close the browser's tab or the browser itself. The alert should say something like "Are you sure you want to leave?" When I manually close the tab ...

Having issues with altering the CSS property in JavaScript

Here is a snippet of PHP code I am working with: <div class="log-in"> <span>Hello '.@$_SESSION['user'].' !</span> <div id="img" onc ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...