Arrays
Douglas Crockford in How JavaScript Works divided array methods into “pure” (ie ones that don’t mutate the original array), and “impure” which often trip me up by often not returning anything while changing the original array.
Pure methods:
- concat
- every
- filter
- find
- findIndex
- forEach
- indexOf
- join
- lastIndexOf
- map
- reduce
- reduceRight
- slice
- some
Impure methods:
- fill
- pop
- push
- shift
- splice
- unshift
Impure methods that should have been pure:
- reverse
- sort
Objects->Arrays, Arrays->Objects
Objects can be represented as an array of [key, value]
arrays using Object.entries(obj)
'[["key1","value1"],["key2",2]]' === JSON.stringify(Object.entries({"key1": "value1", "key2": 2}));
An advantage of [key, value]
is it allows lisp-style code where the key can be found from arr[0]
;
Object.fromEntries() does the inverse:
JSON.stringify(Object.fromEntries([["key1","value1"],["key2",2]])) === JSON.stringify({"key1": "value1", "key2": 2});
If only an array of keys are wanted, there’s Object.keys(obj), and for an array of values there’s Object.values(obj).