How to duplicate elements in a js array?
I came up with something similar to tymeJV's answer
[2, 3, 1, 4].reduce(function (res, current, index, array) {
return res.concat([current, current]);
}, []);
I suppose you could do:
var duplicated = a.map(function(item) {
return [item, item];
}).reduce(function(a, b) { return a.concat(b) });
//duplicated: [2, 2, 3, 3, 1, 1, 4, 4]
Basically you can use flatMap
in ES19
a = [1, 2, 3, 4];
a.flatMap(i => [i,i]); // [1, 1, 2, 2, 3, 3, 4, 4]
Also you can customize the repetitions number like this:
a = [1, 2, 3, 4];
const dublicateItems = (arr, numberOfRepetitions) =>
arr.flatMap(i => Array.from({ length: numberOfRepetitions }).fill(i));
dublicateItems(a, 3);
My reply to the comment below by @user120242 why so complicated? a.flatMap(i => Array(n).fill(i)) find it here
Basically:
a = [2, 3, 1, 4];
b=[];
for(var i = 0; i< a.length;++i){
b.push(a[i]);
b.push(a[i]);
}
a=b;