Search code examples
arraysreact-nativedictionaryjoindelimited

How to return comma delimited string from array, in React Native


I have an array and I want to extract a specific column's values and return the items in a comma-delimited string. What is the best way to go about this? For the below array I would like to get the values of name and return "John,Tim,Mike" Thanks for any assistance

const users = [{
  "name": "John",
  "color": "blue",
},{
  "name": "Tim",
  "color": "red",
},{
  "name": "Mike",
  "color": "green",
}]

I would like to return the results in a comma-delimited string

str = "John,Tim,Mike"

Thanks again for any assistance.


Solution

  • You can map to extract names, then run a join:

    const users = [{
      "name": "John",
      "color": "blue",
    },{
      "name": "Tim",
      "color": "red",
    },{
      "name": "Mike",
      "color": "green",
    }];
    
    const commaSep = users.map(item => item.name).join(', ');
    
    console.log(commaSep);