Skip to content

What is the most elegant way to insert objects between array elements?

I’m sure there are many ways to achieve that but I’m looking for something “elegant”.

a = [
  'a',
  'b',
  'c'
];

magicArrayJoin(a, {value: 255} ); // insert the same object between each item

result ==  [
  'a',
  {value: 255},
  'b',
  {value: 255}
  'c'
];

All proposals are welcome. 🙂

Advertisement

Answer

This worked for me:

 a.map(val = [val, {value: 255}]).flat()
User contributions licensed under: CC BY-SA
4 People found this is helpful