forked from GrosSacASac/JavaScript-Set-Up
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray.js
More file actions
71 lines (55 loc) · 1.71 KB
/
Copy pathArray.js
File metadata and controls
71 lines (55 loc) · 1.71 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
/* Array */
/*How to create an empty Array ?*/
let array;
// same
array = [];
array = Array.of();
array = Array(); // avoid because it is unsafe
// 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
const specificPosition = 5; // remove the 6th element in the array
array.splice(specificPosition, 1);
// 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
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);
}