简体   繁体   中英

How can I modify the last iteration of a Array.map?

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

Use join() :

 const test = [ 'element1', 'element2', 'element3' ]; const asString = test.join(); console.log(asString);

Note : join() 's default separator is a comma ( , )
You can specify a other sepearor as first agument, eg: join('-')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM