-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathArray.js
More file actions
99 lines (76 loc) · 2.4 KB
/
Copy pathArray.js
File metadata and controls
99 lines (76 loc) · 2.4 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* Array */
/*How to create an empty Array ?*/
let array;
// same
array = [];
array = Array.of();
array = Array(); // avoid because it is unsafe
/* How to create an array filled with a given value */
const value = 0;
const wantedLength = 15;
const filled = [];
filled.length = wantedLength;
filled.fill(value);
// set
array[5] = "Hi";
// get
const seventhItem = array[6];
// get the length
const length = array.length;
// add 1 thing at the end
array.push("something");
// add multiple things at the end
array.push(4, 88, 99);
// add an array at the end (inlines the array)
array.push(...[4, 88, 99]);
// add at the begining
array.unshift("JS");
// remove the last thing
array.pop();
array.splice(-1); // alternative
array.length += -1; // alternative
// remove the last thing and store it
const removedLastPart = array.pop();
const removedLastPart2 = (array.splice(-1))[0]; // alternative
// alternative
const newLength = array.length - 1;
const removedLastPart3 = array[newLength];
array.length = newLength;
// remove the first thing and store it
const removedFirstPart = array.shift();
// remove at a specific position, changes the original array
const specificPosition = 5; // remove the 6th element in the array
array.splice(specificPosition, 1); // returns an array with that element
// remove a specific item once, if the item is not there it removes the last
const itemToBeRemoved = "removeMe";
const specificItemPosition = array.indexOf(itemToBeRemoved);
array.splice(specificItemPosition, 1);
// remove a specific item once, safe
const itemToBeRemoved = "removeMe";
const specificItemPosition = array.indexOf(itemToBeRemoved);
if (specificItemPosition !== -1) {
array.splice(specificItemPosition, 1);
}
// replace an item, safe
let array = [1, 2, 3, "removeMe", 10];
const itemToBeRemoved = "removeMe";
const itemToBeInserted = "I am new";
const index = array.indexOf(itemToBeRemoved);
if (index !== -1) {
array.splice(index, 1, itemToBeInserted);
}
// remove duplicates in another array
const a = [0, 1];
const b = [1, 2];
// a and b can be the same
const c = [...new Set([...a, ...b])]; // [0, 1, 2]
// concat 2 arrays
const arrayA = [1, 2, 3];
const arrayB = [4, 5, 6];
const array_AandB = arrayA.concat(arrayB);
// alterantive
const array_AandB = [...arrayA, ...arrayB];
// duplicate array
let copy = Array.from(arrayA);
// only works with primitives,
// for a deep copy see deepCopy from utilsac package