SO Answer / How to clone an array in javascript without using JSON.stringify or JSON.parse?

Link to Q within results

by KooiInc MeHere

HTML

<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>
<div class="solink" data-linkid="25795573"></div>

CSS

code.showObj {
    white-space: pre;
    display: block;
}

JavaScript

var log = Helpers.log2Screen;
var format = new Helpers.Partial(Object.print, null, '  ');

Object.clone = cloneObj;

//a Fruit constructor
var Fruit = function (name){
    this.name = name;
}

// create an Array of Fruit instances
var fruits = 'apple,banana,orange,kiwi,pear'.split(',')
               .map(function(v) {return new Fruit(v);});

log('<h3>Cloning an Array of Objects</h3>');

// cloning by creating a new instance with old data
var fruits2 = fruits.map(function(v) {return new Fruit(v.name);});

// cloning by JSON
var fruits3 = fruits.map(function(v) {return JSON.parse(JSON.stringify(v));});

// original [fruits]  should keep its values after this
fruits2[0].name = 'strange fruit';

//[fruits] and [fruits2] should keep their values after this
fruits3[0].name = 'pineapple';

// cloning by method map/cloneObj
var fruits4 = fruits.map(function(v) {return cloneObj(v);});

// fiddle around with fruits4 values (other fruits[x] keep their values)
fruits4[0] = {name: 'grapes', data: {price: 3, volume: 1}}; 
fruits4[1] = [1,2,3, {name: {pre: 'foo', last: 'bar', date: new Date()}}];
fruits4.push('a string value');

// and clone again, in one go, actually this is a fourth method, the
// using the cloneObj method you don't really need mapping
// Let's use the Obect.clone (static extension)
var fruits5 = Object.clone(fruits4);

// more fiddling: [fruits4] should keep its values
fruits5[0].name = 'tomatoe';
fruits5[0].data = null;
fruits5[1][3].name.test = 'abcd'.split('');
fruits5[1][3].name.date = new Date('2014/03/03 01:00');
fruits5.pop();

log( interpolate (
               'fruits (the original one and only):<br>{fruits}<br><br>'+
               'fruits2 (instances clone, modified):<br>{fruits2}<br><br>'+
               'fruits3 (JSON clone, modified):<br>{fruits3}<br><br>'+
               'fruits4 (`map/cloneObj` method clone, modified):<br>{fruits5}<br><br>'+
               'fruits5 (`Object.clone` method clone (base fruits4), modified):<br>{fruits5}',
       ...