A simple solution is to use reduce() without second argument and without spreading the previous result:

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}

Without second argument, reduce() will start at index 1 instead of 0, and React is perfectly happy with nested arrays.

As said in the comments, you want to only use this for arrays with at least one item, because reduce() without second argument will throw with an empty array. Normally this should not be a problem, since you want to display a custom message saying something like 'this is empty' for empty arrays anyway.

Update for Typescript

You can use this in Typescript (without type-unsafe any) with a React.ReactNode type parameter on .map():

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map<React.ReactNode>(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}
Answer from Maarten ter Horst on Stack Overflow
Top answer
1 of 16
251

A simple solution is to use reduce() without second argument and without spreading the previous result:

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}

Without second argument, reduce() will start at index 1 instead of 0, and React is perfectly happy with nested arrays.

As said in the comments, you want to only use this for arrays with at least one item, because reduce() without second argument will throw with an empty array. Normally this should not be a problem, since you want to display a custom message saying something like 'this is empty' for empty arrays anyway.

Update for Typescript

You can use this in Typescript (without type-unsafe any) with a React.ReactNode type parameter on .map():

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map<React.ReactNode>(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}
2 of 16
36

You can use reduce to combine multiple elements of an array:

React.createClass({
  render() {
     <div>
        this.props.data
        .map(t => <span>t</span>)
        .reduce((accu, elem) => {
            return accu === null ? [elem] : [...accu, ',', elem]
        }, null)
     </div>
  }
})

This initializes the accumulator with null, so we can wrap the first item in an array. For each following element in the array, we construct a new array that contains all previous elements using the ...-operator, add the separator and then the next element.

Array.prototype.reduce()

Discussions

How to merge two array of objects with reactjs?
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Perform .join on value in array of objects
Despite the code being slightly less clean/clear. It is a much more efficient than piping the map function to a join. The reason for this is because Array.map has to loop over each element to return a new array with all of the names of the object in the array. More on stackoverflow.com
🌐 stackoverflow.com
How to join fields of an array of objects in javascript/typescript - Stack Overflow
The join function of an array can only be used on the whole entry, not on fields of the object that is underneath. More on stackoverflow.com
🌐 stackoverflow.com
How to using array.prototype.join in reactjs - javascript
I try how to render react components by using map and join but I could not. ... The function join is only applicable to an Array. Learn more about it here: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/join · THis function will join all the elements (in most of the cases, strings) from the array to a single string. For your specific case since the author name is inside an object ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Educative
educative.io › answers › what-is-the-join-method-of-an-array-in-typescript
What is the join() method of an array in TypeScript?
Lines 2–5: We declare three arrays: names, numbers, and cars and initialize them with elements. Line 8: We use the join() method to combine the elements of names using the separator, " ", and print the returned string to the console. Line 9: We use the join() method to combine the elements of numbers using the separator, "+", and print the returned string to the console.
🌐
TutorialsPoint
tutorialspoint.com › typescript › typescript_array_join.htm
TypeScript - Array join()
join() method joins all the elements of an array into a string. separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma.
🌐
TutorialsPoint
tutorialspoint.com › typescript › typescript_array_concat.htm
TypeScript - Array concat()
concat() method returns a new array comprised of this array joined with two or more arrays. valueN − Arrays and/or values to concatenate to the resulting array. Returns a new array.
🌐
Bobby Hadz
bobbyhadz.com › blog › react-merge-two-arrays
How to merge two Arrays in React.js | bobbyhadz
This process can be repeated with as many arrays as necessary. ... Copied!const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = ['e', 'f']; const arr4 = [...arr1, ...arr2, ...arr3]; // 👇️ ['a', 'b', 'c,' 'd', 'e', 'f'] console.log(arr4); You can use the same approach when setting the state in React. When we use the spread syntax (...), we create a shallow copy of the original array.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › join
Array.prototype.join() - JavaScript - MDN Web Docs
If the array has only one item, then that item will be returned without using the separator. const elements = ["Fire", "Air", "Water"]; console.log(elements.join()); // Expected output: "Fire,Air,Water" console.log(elements.join("")); // Expected output: "FireAirWater" console.log(elements.join("-")); // Expected output: "Fire-Air-Water" ... A string to separate each pair of adjacent elements of the array.
🌐
GitHub
gist.github.com › granmoe › 274c299b792b039deecfb619753ea32c
Ever wanted to join react children like you join an array? · GitHub
export default class MyComponent extends React.Component { render () { return <WithSeparator separator={<Separator className="separator" />}> {this.props.items.map((item, index) => this.renderItem(item, index))} </WithSeparator > // with 3 items, joinChildren returns [<Item>, <Separator>, <Item>, <Separator>, <Item>] } renderItem = (item, index) => { return <Item key={ index } className="item" /> } }
Find elsewhere
🌐
DEV Community
dev.to › fullstackchris › advanced-typescript-a-generic-function-to-merge-object-arrays-18ja
Advanced TypeScript: A Generic Function to Merge Object Arrays - DEV Community
December 9, 2021 - You could explicitly write key / value assignments for the keys that you want to update... or you can leverage JavaScript's built in Object.assign function and TypeScript's generic capabilities to only write one such function for all merging actions you need across your entire app! 😄 · For example, in ReduxPlate, I have two types, IFile, and IEditorSettings: ... IEditorSettings extends IFile and has just one additional property: isActive. When visitors click the "Generate!" button on the MVP page, the response from the server returns an array of objects of type IFile instead of IEditorSettings, since the server is not concerned with the isActive property.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › concat
Array.prototype.concat() - JavaScript - MDN Web Docs
The concat() method of Array instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript-array-join-method
TypeScript Array join() Method - GeeksforGeeks
July 12, 2024 - The Array.join() method in TypeScript is a built-in function used to join all the elements of an array into a single string.
🌐
Codemzy
codemzy.com › blog › joining-arrays-react-components
Joining arrays with JSX and React components - Codemzy's Blog
June 9, 2023 - Nope. Array.join() doesn't work with objects, and it certainly doesn't work with React components.
🌐
Paige Niedringhaus
paigeniedringhaus.com › merge javascript objects in an array with different defined properties
Merge JavaScript Objects in an Array with Different Defined Properties | Paige Niedringhaus
June 6, 2022 - So instead of being able to use the spread operator or Object.assign() to get these events merged into one object, I had to get more creative with a few extra functions and the reduce() method. But it worked - even with TypeScript in the mix. Check back in a few weeks — I’ll be writing more about JavaScript, React, IoT, or something else related to web development.
🌐
Codemzy
codemzy.com › blog › array-join-object-property
Using Array join() on an object property - Codemzy's Blog
May 30, 2023 - You can use Array.join() on an array of objects, but `join()` will only work with strings, so you need to get the property value(s) first. Let's look at some examples.
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Merge Properties of Array Elements with React.js | Pluralsight
September 23, 2020 - This guide shows how to simply loop over a JSON array and merge properties of array elements with JavaScript's advanced array methods `map()` and `filter()`.