How to Clone a Range of Array Elements to a New Array

How do I clone a range of array elements to a new array?

You could add it as an extension method:

public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}
}

Update re cloning (which wasn't obvious in the original question). If you really want a deep clone; something like:

public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
T[] arrCopy = new T[length];
Array.Copy(data, index, arrCopy, 0, length);
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, arrCopy);
ms.Position = 0;
return (T[])bf.Deserialize(ms);
}
}

This does require the objects to be serializable ([Serializable] or ISerializable), though. You could easily substitute for any other serializer as appropriate - XmlSerializer, DataContractSerializer, protobuf-net, etc.

Note that deep clone is tricky without serialization; in particular, ICloneable is hard to trust in most cases.

copy range of elements from an array to another array in C language

You are setting p = g_id. If you want the copy to go to matching locations, you have to set matching offsets on both the local and global arrays.

int *src, *dst;

for (src = id + first, dst = g_id + first; src <= id + last; src++, dst++) {
*dst = *src;
}

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).

Make clone of array (not copy of reference) and modify the new array

arr1 contains objects, so just cloning arr1 is not enough. You need to clone the objects in the arr1 too.

You can use .map() function and the spread operator to create a new array that contains clones of the objects in arr1.





const arr1 = [
{ department: "Lebensmittel", id: "id6", product: "Nudeln", status: false },
{ department: "Ceralien", id: "id5", product: "Marmelade", status: false },
{ department: "Ceralien", id: "id3", product: "Müsli", status: false },
{ department: "Ceralien", id: "id4", product: "Honig", status: false },
{ department: "Molkereiprodukte", id: "id1", product: "Milch", status: false }
];

let testArr = arr1.map(obj => ({...obj}));

testArr.forEach(obj => (obj.status = "test"));

console.log(arr1[0]);
console.log(testArr[0]);
.as-console-wrapper { max-height: 100% !important; top: 0; } 

How do I copy the array elements and also reversing certain elements with Array.Copy() in c#?

First array.

To reverse array you can just call Array.Reverse() after copying:

Array.Copy(SourceArray, 0, DestArray1, 0, 4);
Array.Reverse(DestArray1);

Second array.

if not reversed then Array.Copy() works kind of fine except for the
last element

Because you pass invalid count of elements to copy (last parameter):

Array.Copy(SourceArray, 4, DestArray2, 0, 3); // 3 - elements count, not an index

Simply replace 3 with 4:

Array.Copy(SourceArray, 4, DestArray2, 0, 4); // 4 and it will copy including the last element

How to copy part of an array to another array in C#?


int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • a = source array
  • 1 = start index in source array
  • b = destination array
  • 0 = start index in destination array
  • 3 = elements to copy

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


Related Topics



Leave a reply



Submit