Search code examples
javascriptarraysduplicatesclone

clone js array w/ objects and primitives


Given the array:

['1', {type:'2'}, ['3', {number: '4'}], '5']

I need to make a clone without using the slice, json.parse and other methods.

At the moment, the code is working, but it will not clone objects:

var myArr =['1',{type:'2'},['3',{number:'4'}],'5'];
var arrClone=[];
for(var i=0;i<myArr.length;i++){
if(typeof(myArr[i])==='object')
{
    var arr=[];
    for(var j=0;j<myArr[i].length;j++){
        arr[j]=myArr[i][j];
    }


    arrClone[i]=arr;
}else { arrClone[i]=myArr[i]}

}

Solution

  • You could check if an object is supplied and if so, another check is made for an array. Then retrn either the cloned array or the object, or the value itself.

    function getClone(value) {
        if (value && typeof value === 'object') {
            return Array.isArray(value)
                ? value.map(getClone)
                : Object.assign(
                    ...Object.entries(value).map(([k, v]) => ({ [k]: getClone(v) }))
                );
        }
        return value;
    }
    
    var data = ['1', { type: '2' }, ['3', { number: '4' }], '5'],
        clone = getClone(data);
        
    console.log(getClone(data));