Array Given:
const Collection = [{ id: 1 }, { id: 3 }, { id: 2 }, { id: 4 }]
Required String should be:
string = "1,3,2,4"
I have tried to get from forEach() loop to join() each value and save it in a string variable.
expecting result should be a comma separated string.
2
Answers
The
forEach()
method doesn’t return anything. Instead you want tomap()
each element to itsid
property, and thenjoin()
it:Note that the
join()
method takes care of converting the numbers to strings and adding commas (","
), which are the default separators.Playground link to code
You can use
forEach
, but you would have to pair it with something else.