|
| 1 | +# Array methods cheatsheet |
| 2 | + |
| 3 | +## Adding/Removing elements |
| 4 | + |
| 5 | +- push(...items) <br> |
| 6 | + add elements to the end |
| 7 | + |
| 8 | +```js |
| 9 | +const arr = [1, 2, 3]; |
| 10 | +arr.push(4); |
| 11 | +// arr = [1, 2, 3, 4] |
| 12 | +``` |
| 13 | + |
| 14 | +- pop() <br> |
| 15 | + extracts an element from the end |
| 16 | + |
| 17 | +```js |
| 18 | +const arr = [1, 2, 3]; |
| 19 | +arr.pop(); |
| 20 | +// arr = [1, 2] |
| 21 | +``` |
| 22 | + |
| 23 | +- unshift(...items) <br> |
| 24 | + add items to the beginning (bad for performance) |
| 25 | + |
| 26 | +```js |
| 27 | +const arr = [1, 2, 3]; |
| 28 | +arr.unshift(0); |
| 29 | +// arr = [0, 1, 2, 3] |
| 30 | +``` |
| 31 | + |
| 32 | +- shift() <br> |
| 33 | + extracts from the beginning |
| 34 | + |
| 35 | +```js |
| 36 | +const arr = [1, 2, 3]; |
| 37 | +arr.shift(); |
| 38 | +// arr = [2, 3] |
| 39 | +``` |
| 40 | + |
| 41 | +- concat(...items) <br> |
| 42 | + returns a new array: copy of the current array + `items` |
| 43 | + |
| 44 | +```js |
| 45 | +const arr = [1, 2, 3]; |
| 46 | +const newArr = arr.concat(4, 5); |
| 47 | +const newArr2 = newArr.concat([6, 7]); |
| 48 | +// newArr2 = [1, 2, 3, 4, 5, 6, 7] |
| 49 | +``` |
| 50 | + |
| 51 | +- splice(pos, count, ...items) <br> |
| 52 | + at index `pos` deletes `count` elements and inserts `items` |
| 53 | + |
| 54 | +```js |
| 55 | +const arr = ["a", "*", "*", "d"]; |
| 56 | +arr.splice(1, 2, "b", "c"); |
| 57 | +// arr = ['a', 'b', 'c', d'] |
| 58 | +``` |
| 59 | + |
| 60 | +- slice(start, end) <br> |
| 61 | + creates a new array, copies elements from index `start` till `end` (not inclusive) into it |
| 62 | + |
| 63 | +```js |
| 64 | +const arr = [1, 2, 3, 4, 5]; |
| 65 | +const newArr = arr.slice(1, 4); |
| 66 | +// newArr = [2, 3, 4] |
| 67 | +``` |
0 commit comments