Copy Array by Value

Copy array by value

Use this:

let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});

How to copy all items from one array into another?

The key things here are

  1. The entries in the array are objects, and
  2. You don't want modifications to an object in one array to show up in the other array.

That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.

If the destination array doesn't exist yet...

...use map to create a new array, and copy the objects as you go:

const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);

...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):

const newArray = sourceArray.map(obj => ({...obj}));

That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.

Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:

function naiveDeepCopy(obj) {
const newObj = {};
for (const key of Object.getOwnPropertyNames(obj)) {
const value = obj[key];
if (value && typeof value === "object") {
newObj[key] = {...value};
} else {
newObj[key] = value;
}
}
return newObj;
}
const sourceArray = [
{
name: "joe",
address: {
line1: "1 Manor Road",
line2: "Somewhere",
city: "St Louis",
state: "Missouri",
country: "USA",
},
},
{
name: "mohammed",
address: {
line1: "1 Kings Road",
city: "London",
country: "UK",
},
},
{
name: "shu-yo",
},
];
const newArray = sourceArray.map(naiveDeepCopy);
// Modify the first one and its sub-object
newArray[0].name = newArray[0].name.toLocaleUpperCase();
newArray[0].address.country = "United States of America";
console.log("Original:", sourceArray);
console.log("Copy:", newArray);
.as-console-wrapper {
max-height: 100% !important;
}

Javascript copy array. Changes affect both arrays

When you copy via .slice or [...] it performs a shallow copy, which means the outer array is copied but the inner arrays aren't. You can individually copy each element:

let ans = board.map(v => v.slice()); // copies every 1d array

Need to keep original array values and create copy, change one value in copy but original is changed also?

This is because an array is stored in the heap. Arrays are reference types, therefore if you try to assign an array to a new array, the new array won't be a copy. It will reference to the array storage in the heap.

On of the easiest way to real copy an array is to loop through the array and assign every value by itself to the new array. Therefore the new array get it's own heap storage place but just with the same values as the original one.

Here is a good explanation if you are more interested in this topic:
Link

How to copy array without changing original array?

In your example code, you're working with slices, not arrays.

From the slice documentation:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

When you assign a slice to a variable, you're creating a copy of that descriptor and therefore dealing with the same underlying array. When you're actually working with arrays, it has the behavior you're expecting.

Another snippet from the slice documentation (emphasis mine):

A slice, once initialized, is always associated with an underlying array that holds its elements. A slice therefore shares storage with its array and with other slices of the same array; by contrast, distinct arrays always represent distinct storage.

Here's a code sample (for the slices, the memory address of the first element is in parentheses, to clearly point out when two slices are using the same underlying array):

package main

import (
"fmt"
)

func main() {
// Arrays
var array [2]int
newArray := array
array[0] = 3
newArray[1] = 2
fmt.Printf("Arrays:\narray: %v\nnewArray: %v\n\n", array, newArray)

// Slices (using copy())
slice := make([]int, 2)
newSlice := make([]int, len(slice))
copy(newSlice, slice)
slice[0] = 3
newSlice[1] = 2
fmt.Printf("Slices (different arrays):\nslice (%p): %v \nnewSlice (%p): %v\n\n", slice, slice, newSlice, newSlice)

// Slices (same underlying array)
slice2 := make([]int, 2)
newSlice2 := slice2
slice2[0] = 3
newSlice2[1] = 2
fmt.Printf("Slices (same array):\nslice2 (%p): %v \nnewSlice2 (%p): %v\n\n", slice2, slice2, newSlice2, newSlice2)
}

Output:

Arrays:
array: [3 0]
newArray: [0 2]

Slices (different arrays):
slice (0xc000100040): [3 0]
newSlice (0xc000100050): [0 2]

Slices (same array):
slice2 (0xc000100080): [3 2]
newSlice2 (0xc000100080): [3 2]

Go Playground

Array Copy and add new value

I really don't know how to add in a new value once I copy the array.

You would have to create a new array, copy all the elements of the old array into the new array, and add the new value. Bear in mind, however, that Java ArrayList is more appropriate for such kinds of operations (e.g., add, remove, and so on).

Nonetheless, in your case, to get the output "I Love Coding" you just need to change your code to:

public static void main(String[] args) {

String originalArray[] = {"I", "Love","Java"};
String newArray[] = new String[originalArray.length];

System.arraycopy(originalArray, 0, newArray, 0, 2);
newArray[newArray.length - 1] = "Coding";
System.out.println("Original Array Value: " + Arrays.toString(originalArray));
System.out.println("New Array Value: " + Arrays.toString(newArray));

}

And by the way, can I make the array like this:-

String originalArray[] = {"I Love Java"};

Yes you can. However, it would be now an array with a single string "I Love Java", whereas

String originalArray[] = {"I","Love","Java"}

is an array with three strings, namely "I", "Love", "Java". In this case, you would have to replace the String Java with Coding, without having to copy all the array elements.

public static void main(String[] args) {

String originalArray[] = {"I Love Java"};
String newArray[] = new String[originalArray.length];
newArray[0] = originalArray[0].replace("Java", "Coding");
System.out.println("Original Array Value: " + Arrays.toString(originalArray));
System.out.println("New Array Value: " + Arrays.toString(newArray));

}

How to copy values of a field in Array of object into another array

You can use Array#map() instead: