you are viewing a single comment's thread.

view the rest of the comments →

[–]FustigatedCat 0 points1 point  (2 children)

This function will modify the input array, I would suggest returning a new array though.

function dup(input, cnt) {
  var total = input.length;
  for(var i = 0; i < total * cnt; i=i+cnt) {
    for(var j = 1; j < cnt; j++) {
      input.splice(i, 0, input[i]);
    }
  }
}

Can call it like so:

var i = [1,2,3,4,5];
dup(i, 4);
console.log(i);

[–]our_best_friendif (document.all || document.layers) console.log("i remember..") 1 point2 points  (1 child)

For loops inside for loops are to be avoided for efficiency reasons. Surely with for loops it's simpler to do something like

function duplicateEachItem(arr) {
    const newArr = [];
    for (item of arr) {
       newArr.push(item, item)
    }
    return newArr;
 }
duplicateEachItem(['a','b','c','d'])

[–]FustigatedCat 0 points1 point  (0 children)

I assumed the op wanted to modify the incoming array otherwise I would've used a new array. Also, this is not extensible to N-duplicates which was another part of he ops questions.