Copy Arrays to Array

Copy array by value

Use this:

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

let newArray = oldArray.slice();

console.log({newArray});

Copy Arrays to Array

I try to copy a Int Array into 2 other Int Arrays with

The first thing that is important is that in this line :

unsortedArray2 = unsortedArray;

you do not copy the values of the unsortedArray into unsortedArray2. The = is called the assignment operator

The assignment operator (=) stores the value of its right-hand operand in the storage location,

Now the second thing that you need to know to understand this phenomenon is that there are 2 types of objects in C# Reference Types and Value types

The documentation explains it actually quite nicely:

Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.

The solution can be to use the Array.Copy method.

Array.Copy(unsortedArray, 0, unsortedArray2 , 0, unsortedArray.Length);

The CopyTo method would also work in this case

unsortedArray.CopyTo(unsortedArray2 , 0);

Note:this will work because the content of the array is a value type! If it would be also of reference type, changing a sub value of one of the items would lead also to a change in the same item in the destination array.

Copy array items into another array

Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

Copying Arrays The Right Way

The first example doesn't copy anything. It assigns a reference of the original array to a new variable (array2), so both variables (array1 and array2) refer to the same array object.

The second example actually creates a second array and copies the contents of the original array to it.

There are other easier ways of copying arrays. You can use Arrays.copyOf or System.arraycopy instead of explicitly copying the elements of the array via a for loop.

int[] secondArray = Arrays.copyOf (firstArray, firstArray.length);

or

int[] secondArray = new int[firstArray.length];
System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length);

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;
}

Is there a function to copy an array in C/C++?

Since C++11, you can copy arrays directly with std::array:

std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B

Here is the documentation about std::array

How to copy a array into another array that already has data in it?

You can't increase the size of the original array. But you could create a new array, copy both source arrays into it, and assign your reference variable to it.

For example, here's a sketch of a simple implementation. (An alternative is to use System.arraycopy().)

 float[] newerArray = new float[ newarray.length + arraytobecopied.length ];
for ( int i = 0; i < newarray.length; ++i ) {
newerArray[i] = newarray[i];
}
for ( int i = 0; i < arraytobecopied.length; ++i ) {
newerArray[ newarray.length + i ] = arraytobecopied[i];
}
newarray = newerArray; // Point the reference at the new array

Alternatively, you could use a java.util.ArrayList, which automatically handles growing the internal array. Its toArray() methods make it easy to convert the list to an array when required.

Copying of an array of objects to another Array without object reference in javascript(Deep copy)

Let me understand: you don't want just have a new array, but you want to create a new instance for all objects are present in the array itself? So if you modify one of the objects in the temp array, that changes is not propagated to the main array?

If it's the case, it depends by the values you're keeping in the main array. If these objects are simple objects, and they can be serialized in JSON, then the quickest way is:

var tempArray = JSON.parse(JSON.stringify(mainArray));

If you have more complex objects (like instances created by some your own constructors, html nodes, etc) then you need an approach ad hoc.

Edit:

If you don't have any methods on your newObjectCreation, you could use JSON, however the constructor won't be the same. Otherwise you have to do the copy manually:

var tempArray = [];
for (var i = 0, item; item = mainArray[i++];) {
tempArray[i] = new newObjectCreation(item.localIP, item.remoteIP, item.areaId);
}

Is there any way to copy an array to the same array with less number of elements

You cannot change the size of an array in Java. Therefore, what you are trying to do is impossible.


FWIW: the most concise way to copy to a >>new<< array reducing its size by one (as per your example) is:

int[] arrayB = Arrays.copyOfRange(arrayA, 1, arrayA.length);

And you can copy elements >>within<< an array using a loop, or using System.arrayCopy. The arraycopy javadoc says:

"If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos + length - 1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos + length - 1 of the destination array."

In other words, you don't need to do an explicit double copy.



Related Topics



Leave a reply



Submit