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.


In this article

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!