-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyArray.js
More file actions
executable file
·80 lines (57 loc) · 1.63 KB
/
Copy pathcopyArray.js
File metadata and controls
executable file
·80 lines (57 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// 29. Copy Array Items into Another Array
// 1. Using the Spread Operator (...)
{
const a1 = [1, 2, 3, 4];
const a2 = [...a1, 6, 7, 8, 9];
console.log(a2);
}
// 2. Using slice() Method
// The slice() method is used to create a shallow copy of the a1. It copies all elements from index 0 to the end of the array by default.
{
const a1 = [1, 2, 3, 4, 5];
const a2 = a1.slice();
console.log(a2);
}
// 3. Using Array.concat() Method
{
const a1 = [1, 2, 3, 4, 5];
const a2 = [].concat(a1);
console.log(a2);
}
// 4. Using map() Method
{
const a1 = [5, 10, 15, 20, 25];
const a2 = a1.map((item) => item);
console.log(a2);
}
// 5. Using Array.from() Method
{
const a1 = [1, 2, 3, 4, 5];
const a2 = Array.from(a1);
console.log(a2);
}
// deep copy arrays
// All of the methods mentioned above create shallow copies of arrays. When the array contains objects, a shallow copy means the array structure is copied, but the objects inside the array will still be referenced by both the original and the new array. Here's an example:
{
const arr = [
{ name: "mario", food: "pizza" },
{ name: "luigi", food: "spaghetti" },
];
const arrCopy = [...arr];
console.log(arr === arrCopy); // false
console.log(arr[0] === arrCopy[0]); // true
console.log(arr);
console.log(arrCopy);
console.log(arr === arrCopy); // false
}
// JSON methods
{
const arr = [
{ name: "mario", food: "pizza" },
{ name: "luigi", food: "spaghetti" },
];
const arrCopy = JSON.parse(JSON.stringify(arr));
console.log(arr === arrCopy);
console.log(arr[0] === arrCopy[0]);
console.log(JSON.parse(JSON.stringify(arr)));
}