1

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]}

}
Lee Mac
  • 15,615
  • 6
  • 32
  • 80

2 Answers2

0

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here is a simple implementation without Array methods:

function deepClone(obj) {
    if (typeof obj !== "object" || obj === null) return obj; // primitives
    // It could be an array or plain object
    const result = obj.constructor.name == "Array" ? [] : {}; 
    for (const key in obj) {
        result[key] = deepClone(obj[key]); // recursive call
    }
    return result;
}

// Demo
var myArr =['1',{type:'2'},['3',{number:'4'}],'5'];
var arrClone = deepClone(myArr);
console.log(arrClone);

Note that this only works for simple data types. As soon as you start to work with Dates, regex objects, Sets, Maps, ...etc, you need much more logic. Also think of self references and functions, and how they should be dealt with.

For more advanced cloning see How to Deep Clone in JavaScript, but expect the use of several methods.

trincot
  • 317,000
  • 35
  • 244
  • 286