How to copy all items from one array into another?
The key things here are
- The entries in the array are objects, and
- 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;
}
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).
Copy the elements of one array into another array
int arr1[10],arr2[10];
int i , n ;
// assigning 10 to n
n = 10;
// initializing arr1
for(i=0; i<n; i++)
{
arr1[i]=i;
}
// copying elements of arr1 into arr2. we want each element of arr1 to be copied into arr2.
for(i=0; i<n; i++)
{
arr2[i]=arr1[i];
}
printf("NOW WE WILL PRINT arr2: \n\n");
for(i=0;i<n;i++)
{
printf("%d \n", arr2[i]);
}
I have initialized arr1 and copied the elements of arr1 to arr2 in addition to incorporating the edits pointed out in the comments.
Copying array into array into another array (of strings), duplicate its content in C
Every string in C needs terminating zero. So the length of your array in too small to accommodate the string and the program invokes the UB.
Change to:
#include <stdio.h>
#include <string.h>
int main()
{
char source[14] = "Hello, World!";
char destination[14];
memcpy(&destination, &source, 14);
printf("%s\n", destination);
return 0;
}
https://godbolt.org/z/Z_yyJX
Copy only certain elements in one array to another array in javascript
You can simply do it using Array.map
.
var source = [
{
"personId": 1,
"personName": "Steve",
"CarName": "Swift",
"Price": "30L",
"OwnerType": "FirstHand",
"Address" : "xxx yyyy zzzz",
"Model" : "2015"
},
{
"personId": 2,
"personName": "Mike",
"CarName": "Breeza",
"Price": "40L",
"OwnerType": "SecondHand",
"Address" : "yyy uuu tttt",
"Model" : "2013"
},
{
"personId": 3,
"personName": "Elle",
"CarName": "Innova",
"Price": "70L",
"OwnerType": "FirstHand",
"Address" : "TTT RRR EEEE",
"Model" : "2018"
}
];
// First Way
var output1 = source.map((item) => ({
personName: item.personName,
CarName: item.CarName,
Price: item.Price,
Address: item.Address,
Model: item.Model
}));
console.log('Output1');
console.log(output1);
// Second Way
var output2 = source.map(({ personId, OwnerType, ...item }) => ({
...item
}));
console.log('Output2');
console.log(output2);
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);
}
How can I copy the elements on an array into another array with a different size?
Because in your changeCapacity function you are not updating the capacity field with the newCapacity being passed.
public void changeCapacity(int newCapacity) {
bag = Arrays.copyOfRange(bag, 0, newCapacity);
capacity = newCapacity;
}
Just replace your changeCapacity function with above code and it should work fine.
push the contents of array into another array without looping
You can spread
the content of both arrays into the new array
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
// prints [1,2,3,4,5,6]
Spreading arr2
into arr1
also works.
arr1.push(...arr2);
console.log(arr1);
// prints [1,2,3,4,5,6]
So changing
ordersArr.push(tOrders)
to
ordersArr.push(...tOrders);
should work.
For a full answer:
let ordersArr = [];
let orders = {
foo: [
{x: 1, b: 2},
{y: 1, c: 3},
{a: 2, d: 4}
]
}
orders2 = {
foo: [
{x: 2, b: 3},
{y: 5, c: 4},
{a: 3, d: 6}
]
}
ordersArr.push(...orders.foo, ...orders2.foo);
Related Topics
How to Group by and Sum an Array of Objects
Differencebetween a User and a Guildmember in Discord.Js
How to Debug JavaScript/Jquery Event Bindings with Firebug or Similar Tools
Can't Bind to 'Ngmodel' Since It Isn't a Known Property of 'Input'
How to Remove All Line Breaks from a String
How to Determine User's Locale Within Browser
Extract Hostname Name from String
JavaScript Before Leaving the Page
How to Escape Regular Expression Special Characters Using JavaScript
Differencebetween String Primitives and String Objects in JavaScript
How Does JavaScript's Sort() Work
How to Send a Variable Number of Arguments to a JavaScript Function
How to Capture an Arbitrary Number of Groups in JavaScript Regexp
Why Does JavaScript Handle the Plus and Minus Operators Between Strings and Numbers Differently
Array.Fill(Array) Creates Copies by References Not by Value
How to Parse JSON Using Node.Js