Home > database >  duplicate elements of an array in JavaScript
duplicate elements of an array in JavaScript

Time:09-18

How to duplicate elements of an array in JavaScript and add them to the same array.

    function duplicate(arr) {
    // Write Logic here
    var position,lengtharr = arr.length;
    for(var i=0;i<lengtharr;  i){
        arr[position] = arr[i];
        position  ;
    }
    
    return arr;
}

var arr=[1,2];

console.log(duplicate(arr));

Please explain why the above code is not working. I'm getting "Incorrect Output" as error.

Also, I've come up with another way as shown below. But I'd like to know what's wrong with this approach.

function duplicate(arr) {
    // Write Logic here
    var lengtharr = arr.length;
    for(var i=0;i<lengtharr;  i){
        arr.push(arr[i]);
    }
    
    return arr;
}

var arr=[1,2];

console.log(duplicate(arr));

Thank you

CodePudding user response:

The reason is var position,lengtharr = arr.length which will make position not as you exepcted,change it to position = lengtharr = arr.length

  function duplicate(arr) {
    // Write Logic here
    var position = lengtharr = arr.length;
    for(var i=0;i<lengtharr;  i){
        arr[position] = arr[i];
        position  ; 
    }
    
    return arr;
}

var arr=[1,2];

console.log(duplicate(arr));

CodePudding user response:

An alternative approach would be to use push to add elements to the end of the array. That way you don't need that extra position variable.

function duplicate(arr) {
  const len = arr.length;
  for (let i = 0; i < len;   i) {
    arr.push(arr[i]);
  }
  return arr;
}

let arr= [1, 2];

console.log(duplicate(arr));

CodePudding user response:

You can achieve this by using Spread syntax (...)

Try this :

function clone(arr) {
  arr.push(...arr);
  return arr;
}

var arr=[1,2];

console.log(clone(arr));

  • Related