Arrays
See Array cheatsheet on ShortCutFoo website.
Read
myArray = ['a', 'b', 'c', 'd']
Get length.
> myArray.length
4
Get element - returns one element.
> myArray[index]
> myArray[1]
'b'
Slice - returns an array of elements.
> myArray.slice(start, end)
[ ... ]
> myArray.slice(1, 3)
[ 'b', 'c' ]
Leave out end
.
> myArray.slice(start)
> myArray.slice(1)
[ 'b', 'c', 'd' ]
Get last element
Use hard bracket slicing
> myArray = ['a', 'b', 'c', 'd']
> myArray[myArray.length - 1]
'd'
> myArray = ['a']
> myArray[myArray.length - 1]
'a'
In Python you simply use a negative index my_list[-1]
, but in JS that gives a undefined
.
Use slice
You can use a negative index here.
> myArray = ['a', 'b', 'c', 'd']
> myArray.slice(-1)
[ 'd' ]
Warning - this returns an array, not a string, so do this.
> myArray.slice(-1)[0]
'd'
Update
Mutate element.
> myArray[index] = value
See also Pop, Push, Shift and Unshift Array Methods in JavaScript
Modify end
Remove last element.
> myArray.pop();
Insert element at the end. i.e. append.
> myArray.push(obj)
Modify at the start
Remove from the beginning. Like Python’s list.pop(0)
. Returns new length.
> myArray.shift()
Insert at the start. Like Python’s list.insert(0, obj)
. Returns new length.
> myArray.shift(obj)
Change order
Reverse.
> myArray.reverse()
Sort. See Sort for more info, as this will not sort numbers properly.
> myArray.sort()
Join arrays
Concatenate arrays.
> myArrayA.concat(myArrayB)
Join elements using a separator e.g. ', '
. This will return a single string.
> myArray.join(sep)
Map, reduce, filter
Return a new object after applying transformation. The old object is no affected, unless you reassign over the same name.
Examples:
myArray.map((x) => x*2)
myArray.reduce((x, y) => x + y)
myArray.filter((x) => x > 2)