Currently, I have the following map
Array.map(i => `${i},`)
It returns
element1,element2,element3,
But I would need it to return
element1,element2,element3
Avoiding the last comma.
How can I do that in a functional way?
That better approach to solving this particular problem is probably to use join
and not map
.
However, to solve this with map, look at the other arguments passed to the callback:
map((element, index, array) => { ... } )
You can determine if you are on the last element using index === array.length - 1
How can I do that in a functional way?
console.log( ['a', 'b', 'c', 'd'].reduce((x, y) => `${x},${y}`) )
You can also use .toString()
or .join()
like this.
const arr = [ 'element1', 'element2', 'element3' ]; console.log(arr.toString()); console.log(arr.join()); // The same as console.log(arr.join(','));
The
toString()
method returns a string with all the array values, separated by commas .
The
join()
method returns the array as a string. The elements will be separated by a specified separator. The default separator is a comma (,).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.