cheatsheets/js-array.md

104 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

2013-10-14 04:36:58 +02:00
---
2017-10-27 06:34:47 +02:00
title: JavaScript Arrays
2015-11-24 05:48:01 +01:00
category: JavaScript
2013-10-14 04:36:58 +02:00
---
2017-10-27 06:34:47 +02:00
### Arrays
2013-10-14 03:55:21 +02:00
2017-10-27 06:34:47 +02:00
```bash
list = [a,b,c,d,e]
```
{: .-setup}
2013-10-14 03:55:21 +02:00
2017-10-27 06:34:47 +02:00
```bash
list[1] // → b
list.indexOf(b) // → 1
2022-08-11 23:41:13 +02:00
list.lastIndexOf(b) // → 1
list.includes(b) // → true
2017-10-27 06:34:47 +02:00
```
2013-10-14 03:55:21 +02:00
### Subsets
2017-10-27 06:34:47 +02:00
#### Immutable
2013-10-14 03:55:21 +02:00
2017-10-27 06:34:47 +02:00
```bash
list.slice(0,1) // → [a ]
list.slice(1) // → [ b,c,d,e]
list.slice(1,2) // → [ b ]
```
#### Mutative
```bash
re = list.splice(1) // re = [b,c,d,e] list == [a]
re = list.splice(1,2) // re = [b,c] list == [a,d,e]
```
2013-10-14 03:55:21 +02:00
### Adding items
#### Immutable
2017-10-27 06:34:47 +02:00
```bash
list.concat([X,Y]) // → [_,_,_,_,_,X,Y]
2017-10-27 06:34:47 +02:00
```
#### Mutative
2013-10-14 03:55:21 +02:00
2017-10-27 06:34:47 +02:00
```bash
list.push(X) // list == [_,_,_,_,_,X]
list.unshift(X) // list == [X,_,_,_,_,_]
list.splice(2, 0, X) // list == [_,_,X,_,_,_]
2017-10-27 06:34:47 +02:00
```
2013-10-14 03:55:21 +02:00
2015-01-28 02:01:00 +01:00
### Inserting
2015-10-15 12:55:41 +02:00
2017-10-27 06:34:47 +02:00
```bash
// after -- [_,_,REF,NEW,_,_]
list.splice(list.indexOf(REF)+1, 0, NEW))
```
2015-01-28 02:01:00 +01:00
2017-10-27 06:34:47 +02:00
```bash
// before -- [_,_,NEW,REF,_,_]
list.splice(list.indexOf(REF), 0, NEW))
```
2015-01-28 02:01:00 +01:00
2014-07-07 04:26:04 +02:00
### Replace items
2017-10-27 06:34:47 +02:00
```bash
list.splice(2, 1, X) // list == [a,b,X,d,e]
```
2014-07-07 04:26:04 +02:00
### Removing items
2013-10-14 03:55:21 +02:00
2017-10-27 06:34:47 +02:00
```bash
list.pop() // → e list == [a,b,c,d]
list.shift() // → a list == [b,c,d,e]
list.splice(2, 1) // → [c] list == [a,b,d,e]
```
2013-10-14 03:55:21 +02:00
2015-05-26 09:14:23 +02:00
### Iterables
2017-10-27 06:34:47 +02:00
```bash
.filter(n => ...) => array
```
2022-08-11 23:41:13 +02:00
```bash
.forEach(n => ...)
```
2017-10-27 06:34:47 +02:00
```bash
.find(n => ...) // es6
.findIndex(...) // es6
```
```bash
.every(n => ...) => Boolean // ie9+
.some(n => ..) => Boolean // ie9+
```
```bash
.map(n => ...) // ie9+
.reduce((total, n) => total) // ie9+
.reduceRight(...)
```