Array
An object type that is a dynamic array.
Creating Arrays
const arr = [1, 2, 3];
arr;
[1, 2, 3]
Indexing
['a', 'b', 'c'][1];
'b'
['a', 'b', 'c'].at(-1);
'c'
Indexing out of bounds resolves to undefined
[][0];
undefined
['a', 'b', 'c'].at(7);
undefined
Length
['a', 'b', 'c'].length;
3
Sorting
String Coercion
The default sort comparator converts values to strings before comparing.
[10, 5, 4, 3, 2, 1].sort();
[1, 10, 2, 3, 4, 5]
A custom comparator can be used.
[10, 5, 4, 3, 2, 1].sort((a, b) => a - b);
[1, 2, 3, 4, 5, 10]
JavaScript's sort has sort stability.
const party = [
{ name: 'ditto', level: 12 },
{ name: 'charmander', level: 8 },
{ name: 'bulbasaur', level: 8 },
{ name: 'abra', level: 12 }
];
party.sort(
(a, b) => a.name.localeCompare(b.name));
// sorted by name
[
{ name: 'abra', level: 12 },
{ name: 'bulbasaur', level: 8 },
{ name: 'charmander', level: 8 },
{ name: 'ditto', level: 12 }
]
party.sort((a, b) => a.level - b.level);
// name order is preserved for values
// with equal level
// sorted by level then name
[
{ name: 'bulbasaur', level: 8 },
{ name: 'charmander', level: 8 },
{ name: 'abra', level: 12 },
{ name: 'ditto', level: 12 }
]
Functional Programming
Filter
filter
only consider a value's truthiness instead of strictly checking if the value is true
.
[1, 2, 3, 4, 5].filter(x => x % 2)
[1, 3, 5]
[1, 0, true, false, 'hi', '']
.filter(x => x);
[1, true, 'hi']
Map
[1, 2, 3, 4, 5].map(x => x * 2);
[2, 4, 6, 8, 10]
Reduce
[1, 2, 3, 4, 5]
.reduce((acc, cur) => acc + cur, 0);
15
[].reduce((acc, cur) => acc + cur);
❌ Uncaught TypeError: Reduce of empty array
with no initial value
Every
[1, 2, 3, 4, 5].every(x => x > 2);
false
Some
[1, 2, 3, 4, 5].some(x => x > 2);
true
Modification
Update by index
const arr = ['a', 'b', 'c'];
arr[1] = 'new';
arr[3] = 'new2';
arr;
['a', 'new', 'c', 'new2']
Push (add to end)
const arr = ['a', 'b', 'c'];
arr.push('d');
4
arr;
['a', 'b', 'c', 'd']
Pop (remove from end)
const arr = ['hello world'];
arr.pop();
'hello world'
arr.pop();
undefined
Unshift (add to beginning)
const arr = ['a', 'b', 'c'];
arr.unshift('first');
4
arr;
['first', 'a', 'b', 'c']
Shift (remove from beginning)
const arr = ['a', 'b'];
arr.shift();
'a'
arr.shift();
'b'
arr.shift();
undefined