1

This question has been asked here and more importantly here. I tried all the answers and none solved my issue. It's very basic.

I have the following array. My various attempts at copying do not persist after splicing, or performing any destructive action. Even the copies are mutated. How can I copy this so the original version persists?

var arrs = [ [ 3 ], [ 7, 4 ], [ 2, 4, 6 ], [ 8, 5, 9, 3 ] ]

var arrsCopy1 = arrs.slice()

var arrsCopy2 = arrs.map(arr => {
  return arr
})

var arrsCopy3 = [...arrs]


//test one of the copies
arrsCopy3.forEach(arr => {
  return arr.splice(0, arr.length)
})
arrs, arrsCopy1, arrsCopy2, arrsCopy3 => [[],[],[],[]]

Here is a fiddle that demos my problem (using reverse() instead of splice)

Mote Zart
  • 861
  • 3
  • 17
  • 33
  • Calling out myself for duplication https://stackoverflow.com/questions/41786946/splice-doesnt-copy-array-of-objects?noredirect=1&lq=1 – Mote Zart Feb 28 '19 at 23:46

3 Answers3

2

You could do it recursively

const copyArr = (element) => {
    //If the element is a primitive
    if (element !== Object(element)) {
        return element;
    //The element is an array
    } else {
        return element.map(subelement => copyArr(subelement));
    }
}
Tiu Wee Han
  • 59
  • 1
  • 3
0

Try using JSON methods:

var arrCopy = JSON.parse(JSON.stringify(arr));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

I just found this and it seems to solve the issue.

I was thrown off my the JSON.parse.

var clonedArray = JSON.parse(JSON.stringify(originalArray));

Mote Zart
  • 861
  • 3
  • 17
  • 33