0

I currently have an array in angular that I would like to change the structure of. Example array:

0: "Car 1"
1: "Car 2"
2: "Car 3"
3: "Car 4"
4: "Car 5"
5: "Car 6"

I would like to convert it to Car1,Car2,Car3,Car4,Car5 so that I can use the IndexOf() function for each comma.

Elidor00
  • 1,271
  • 13
  • 27
Matt
  • 45
  • 2
  • 8
  • What is your end goal exactly? Why do you need to use `indexOf` for commas? – Octavian Mărculescu May 30 '22 at 07:57
  • 1
    Search after join. And before joining the items, remove the space (if necessary) with f. e. map. – derstauner May 30 '22 at 07:59
  • Does this answer your question? [Easy way to turn JavaScript array into comma-separated list?](https://stackoverflow.com/questions/201724/easy-way-to-turn-javascript-array-into-comma-separated-list) – Yong Shun May 30 '22 at 08:48

2 Answers2

1
let yourString = yourArray.map(e => e.replace(/\s/g, "")).join(",")
Benoit Cuvelier
  • 806
  • 7
  • 23
  • 1
    [`.trim()`](https://www.w3schools.com/jsref/jsref_trim_string.asp) only remove the leftmost and rightmost space, but not the space in between words. – Yong Shun May 30 '22 at 08:52
1
let array = [ "Car 1" , "Car 2"  ,"Car 3" , "Car 4" , "Car 5"  ];
let newString = array.map(e => e.replace(/\s/g, '')).join(",")

Output will be - Car1,Car2,Car3,Car4,Car5