How do I make a copy of an array with one difference?

Viewed 51

I want the function to make a copy of an array with the exception it has the mouse position in it. This is my code so far.

mousearray = originalarray;
mousearray[mousex][mousey] = "Your mouse is here";

This doesn't work if I loop it every frame, it seems like the original array gets changed too. How do I fix this?

3 Answers

When you write

mousearray = originalarray;

mousearray doesn't become a copy of that array, it just is a new reference to the same array, thus changing mousearray also changes originalarray cause it is the same.

To truly make a copy, there are two ways:

mousearray= JSON.parse(JSON.stringify(originalarray));
// or
mousearray = _.cloneDeep(originalarray);

Note that the second way requires that you install lodash (npm package).

You can use array destructuring.

const originalArray = [1,2,3,4];
const copyArray = [...originalArray];
///
copyArray.push('hello');
console.log(copyArray); // --> [1,2,3,4,'hello']
console.log(originalArray); // --> [1,2,3,4]

Edit: Another way is to use concat. If you are on an older browser you should prefer this method:

const originalArray = [1,2,3,4];
const copyArray = [].concat(originalArray);
///
copyArray.push('hello');
console.log(copyArray); // --> [1,2,3,4,'hello']
console.log(originalArray); // --> [1,2,3,4]

Edit 2: Since above methods only make a new array instance with virtually same elements. It does not create a true copy. If array has objects, then destructuring or concat methods will copy the references only. There are two ways you can create a true copy.

  1. Use a recursive solution to create separate instances of children as well. Often you will find such a solution in libraries like lodash or jQuery.

  2. Use JSON.parse(JSON.stringify(arr)) hack. Note that this is just a hack and does not always work (esp. if your array or object has circular references).

Multidimensional Array copy with new

var oldArray = [
  ["a","b", {id:1}],
  ["x", "y", ["Role", "Dev"]]
];

// clone "old" Array
var newArray = JSON.parse(JSON.stringify(oldArray));

newArray[0][0] = "GMK";
newArray[0][1] = "Hussain";

console.log('OLD ARRAY')
console.log(oldArray)

console.log('NEW ARRAY')
console.log(newArray)

Short and simplest solution with concat

var oldArray = ["a","b"];

var newArray = ["new"];

var oldAndNewArray = [...oldArray].concat(newArray);

console.log( oldAndNewArray );

Related