flat
flat() merges nested arrays into one level.
const nested = [1, [2, 3], [4, [5]]];
console.log(nested.flat()); // → [1, 2, 3, 4, [5]]
console.log(nested.flat(2)); // → [1, 2, 3, 4, 5]
console.log(nested.flat(Infinity)); // → [1, 2, 3, 4, 5]
The argument is how many levels to flatten. The default is 1.
flatMap
flatMap() is map() followed by flat() (one level), in one step. Handy when each item turns into several items, or into none.
const sentences = ["hello world", "good morning"];
console.log(sentences.map(s => s.split(" ")));
// → [["hello", "world"], ["good", "morning"]]
console.log(sentences.flatMap(s => s.split(" ")));
// → ["hello", "world", "good", "morning"]
Returning an empty array from the callback removes the item:
const numbers = [1, 2, 3, 4];
const result = numbers.flatMap(n => (n % 2 === 0 ? [n, n * 10] : []));
console.log(result); // → [2, 20, 4, 40]
Array.from
Array.from() makes a real array from something array-like or iterable: a string, a Set, a Map, a list of DOM elements, or even just a length.
console.log(Array.from("abc")); // → ["a", "b", "c"]
console.log(Array.from(new Set([1, 1, 2]))); // → [1, 2]
console.log(Array.from({ length: 3 }, (_, i) => i * 2)); // → [0, 2, 4]
The second argument is an optional mapping function, which makes Array.from({ length: n }, ...) a neat way to create a range or a grid.
Turning DOM lists into arrays
document.querySelectorAll() returns a NodeList. It has forEach, but not map or filter. Convert it.
<p class="item">One</p><p class="item">Two</p>
<script>
const items = Array.from(document.querySelectorAll(".item"));
console.log(items.map(el => el.textContent)); // → ["One", "Two"]
</script>
You can also use the spread syntax: [...document.querySelectorAll(".item")].
Removing duplicates
const tags = ["js", "css", "js", "html", "css"];
const unique = Array.from(new Set(tags));
console.log(unique); // → ["js", "css", "html"]
You will meet Set properly in Set and WeakSet.