How to insert values in between every item in an array

In React, you can only return one JSX element (Edit: Not any more!), so inserting spacers between items is awkward.

Gav McKenzie
Author
Gav McKenzie
Published
Aug 28, 2018
Topics
Industry

I didn’t want to loop through the array and update it so it was lodash to the rescue.

_.flatMap([1,2,3,4], (value, index, array) =>
array.length -1 !== index // check for the last item
? [value, "s"]
: value
);

Produces:

[1, "s", 2, "s", 3, "s", 4]

Which is really neat, concise and declarative!

Etch is a web software consultancy based in the UK©2012-2024 Etch Software Ltd