TIL: How to insert values in between every item in an array
1 min readAug 20, 2018
In React, you can only return one JSX element (Edit: Not any more!), so inserting spacers between items is awkward.
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!
At Etch we’re always learning so we can continue to build awesome software.
Let’s see if we can help your team today hey@etch.co