Search code examples
javascriptmongodbmongodb-shell

How to Clone Array To Another Array in Mongo Shell


I have some query to accomplish with some array.

In MongoDB Shell

var array1 = [1,2,3,4];
var array2 = [];

array2 = array1.Clone();

There is no Clone() function in mongodb shell. How can i clone it to another array ?


Solution

  • you can try array.slice(0), this will clone your array number. Another way of cloning using [spread][1] operator ES6.

    var arr = [1, 2, 3]
    var cloned = arr.splice(0)
    
    var arr2 = [1, 2, 3, 4]
    var cloned2 = [...arr2]
    
    console.log('cloned:', cloned)
    console.log('cloned 2:', cloned2)