Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a clone of the following array rather than a reference? [duplicate]

Tags:

javascript

The code (a simple replace loop):

fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err

  data = data.split('\n\n')
  var tree = data

  for (var i = 0; i < tree.length; ++i) {
    if (tree[i].match(/^#/g)) {
      data[i] = data[i]
        .replace(/^#### (.*)/gm, '<h4>$1</h4>')
        .replace(/^### (.*)/gm, '<h3>$1</h3>')
        .replace(/^## (.*)/gm, '<h2>$1</h2>')
        .replace(/^# (.*)/gm, '<h1>$1</h1>')
    }
  }

  data = data.join('\n\n')
  tree = tree.join('\n\n')

  console.log(data)
  console.log(tree)

So in this case both data and tree have the same output:

<h1>Test</h1>

<h2>Test</h2>

Lorem "**ipsum?**" dolor 'sit!' amet

Anooo

* * *

"Ipsum?" "'**dolor**'" *sit!* amet, consetetur
eirmod tempor--invidunt **ut** labore

Anothes

What I want to do is to preserve the original value of data in tree so that only data changes but not tree.

How to do that?

tree should remain like this:

# Test

## Test

Lorem "**ipsum?**" dolor 'sit!' amet

Anooo

* * *

"Ipsum?" "'**dolor**'" *sit!* amet, consetetur
eirmod tempor--invidunt **ut** labore

Anothes
like image 674
alexchenco Avatar asked Mar 24 '15 13:03

alexchenco


People also ask

How do you create a clone array?

You can use a for loop and copy elements of one to another one by one. Use the clone method to clone an array. Use arraycopy() method of System class. Use copyOf() or copyOfRange() methods of Arrays class.

How do you clone an array in Python?

To create a deep copy of an array in Python, use the array. copy() method. The array. copy() method does not take any argument because it is called on the original array and returns the deep copied array.

How do I clone an array in C#?

The Clone() method in C# is used to clone the existing array. Firstly, set the array to be cloned. string[] arr = { "Web", "World"}; Now clone the array created above using the array.

What is clone method in an array?

The references in the new Array point to the same objects that the references in the original Array point to. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements. The clone is of the same Type as the original Array.


2 Answers

Use Array.prototype.slice().

The slice() method returns a shallow copy of a portion of an array into a new array object.

var tree = data.slice();

like image 114
Rodrigo Siqueira Avatar answered Oct 05 '22 23:10

Rodrigo Siqueira


Use a hack

var tree = data.slice(0)

It may be wrapped to a separate function/method.

like image 41
phts Avatar answered Oct 05 '22 23:10

phts