Duplicating an array's elements using functional programming

  • A+
Category:Languages

I'm trying to duplicate each element in an array, but using functional style.

I have this currently:

["a", "b", "c"] 

And I'm getting this:

["a","a","b","b","c","c"] 

So far I have tried the following, mapping each element to an array, then using flat() to get a 1d array. Is there a cleaner way because it feels like I'm abusing map and flat.

["a", "b", "c"].map(item => [item, item]).flat(); 

Is there a better way to do this?


I was trying to provide a example as simple as possible but left some details out. The real input is not sorted because elements are not comparable. It's something like:

[   {     a:"a"     b:"b"   },   {     c: 1     d: 2   },   {     apple: {},     sellers: ["me", "her"]   } ] 

The duplicated result should be something like this, where duplicated elements are next to each other:

[   {     a:"a"     b:"b"   },   {     a:"a"     b:"b"   },   {     c: 1     d: 2   },   {     c: 1     d: 2   },   {     apple: {},     sellers: ["me", "her"]   },   {     apple: {},     sellers: ["me", "her"]   } ] 

 


You can use the function reduce and concatenate the same object on each iteration.

let array = ["a", "b", "c"],     result = array.reduce((a, c) => a.concat(c, c), []);      console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: