I have an array called a
and I want to insert an element after every nt-h
elements of the array a
. For example, I want to put the string XXX
after each 3
elements of the array a
and as result get a new array b
as shown on the next example:
let a = [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ];
let b = [undefined, "", 0, "XXX", [], "ee", false, "XXX", null, {}, Date(), "XXX", true, (z)=>2*z, [], "XXX", NaN];
console.log(a, b);
I have tried to do it in this way:
b = [];
a.map((x, i) => b.push((i + 1) % 3 ? x : "XXX"));
https://jsfiddle.net/Lamik/vjfaqn3u/16/
However, there is a problem: The output b
array has the same length as input a
which is wrong. Any idea or alternative solution?
(UPDATE: in-place solutions are also ok; I cut array a
)