Create array from iterable (e.g. Set, Map)
Array.from(new Set([“foo”, “bar”, “baz”, “foo”]));
Check if arr is an array
Array.isArray(arr)
Truncate array to only 3 elements
a.length = 3
Add/Remove single element from front/back of an array arr (all methods)
arr.push(5);
arr.pop();
arr.unshift("one");
arr.shift();Add multiple elements to the front / back of an array arr
arr.push(1, 2, 3); arr.unshift(1, 2, 3);
Add one array to another (all methods)
["1", "2", "3"].concat("a", "b", "c");
a.concat(b)
[...[1, 3, 2], ...[4, 5, 7]]
// Note:
// [1, 2, 3] + [3, 4, 5]
// will add string representations resulting in '1,2,33,4,5Join elements of an array with -
["1", "2", "3"].join("-");
All array search methods
arr.indexOf("b", 3);
arr.lastIndexOf("b", 3);
arr.find((e) => e > 10); // returns THAT ELEMENT
arr.findIndex((e) => e > 10); // returns index
arr.findLast((e) => e > 10);
arr.findLastIndex((e) => e > 10);Check if 2 is in array arr
arr.includes(2);
Reverse and sort an array (in place and with copy)
arr.reverse(); // in place cont reversedArr = arr.toReversed(); const sorted = arr.toSorted(); arr.sort(); // in place
Create array of 10 elements all with value 4
const tenFours = Array(10).fill(4)
All iterative array methods, args where necessary
And what they do
arr.forEach arr.map arr.flatMap arr.filter arr.every arr.some reduce( (accumulator, currentValue) => accumulator + currentValue, initialValue, ); arr.reduceRight
Get subarray
months.slice(1, 3); // Indexes [1, 3)
What is splice
// Splice (splice = splot) // >> splice(start, deleteCount, item1, item2, /* …, */ itemN) // Remove at index [1] 2 elements, replace with 'a' and 'b', returns removed elements const removed = months.splice(1, 2, "a", "b"); // [1, "a", "b", 4, 5]
Convert ArrayBuffer to regular array of 32-bit integers
let buffer = new ArrayBuffer(16); let int32View = new Int32Array(buffer); const normalArray = Array.from(int32View);
abeverythingElse (as an array)In single line
const [a, b, …everythingElse] = [0, 1, 1, 2, 3, 5, 8];
Methods on Map
* Add and remove elements
* Read elements
* Check if element in a map
* Remove all elements
* Get length
sayings.set("dog", "woof");
sayings.delete("dog");
sayings.get("dog");
sayings.has("bird");
sayings.clear();
sayings.size;Methods on Set
* Add and remove elements
* Check if element in a set
* Remove all elements
* Get length
mySet.add(1); mySet.delete(1); mySet.has(1); mySet.clear(); mySet.size;
Iterate all Map entries
for (let [key, value] of sayings) {
console.log(key + " goes " + value);
}Iterate all Set entries
for (let item of mySet) console.log(item);
How to use async callback in map
const itemsPromises = [1, 2, 3].map(async (i) => i.toString()) await Promise.all(itemsPromises);
Flatten container to 1D
(Something like [0, 1, 2, [3, 4]])
Use flat(depth)
[0, 1, 2, [3, 4]].flat()