What is the most elegant way to insert objects between array elements?
One-liner using plain ES6:
const interleave = (arr, thing) => [].concat(...arr.map(n => [n, thing])).slice(0, -1)
Usage:
interleave(['foo', 'bar', 'baz'], 'avocado')
Prints:
> ["foo", "avocado", "bar", "avocado", "baz"]
In my opinion the most elegant way to do this is the following one:
ES6 syntax version
const insertIntoArray = (arr, value) => {
return arr.reduce((result, element, index, array) => {
result.push(element);
if (index < array.length - 1) {
result.push(value);
}
return result;
}, []);
};
Usage:
insertIntoArray([1, 2, 3], 'x'); // => [1, 'x', 2, 'x', 3]
You can do it with flatMap. It can be found from lodash for example
_.flatMap([1,2,3,4], (value, index, array) =>
array.length -1 !== index // check for the last item
? [value, "s"]
: value
);
ouputs
[1, "s", 2, "s", 3, "s", 4]
Update
Array#flatMap proposal is in the works so in future this should work:
[1, 2, 3, 4].flatMap(
(value, index, array) =>
array.length - 1 !== index // check for the last item
? [value, "s"]
: value,
);