A few more tools worth knowing:
// includes: is it in there?
console.log([1, 2, 3].includes(2));
// flat: flatten nested arrays
console.log([[1, 2], [3, 4], [5]].flat());
// Array.from: make an array from something else
console.log(Array.from("hey"));
console.log(Array.from({ length: 5 }, (_, i) => i * 10));
// join, after a map
console.log(["a", "b", "c"].map((x) => x.toUpperCase()).join("-"));
It prints
true [ 1, 2, 3, 4, 5 ] [ 'h', 'e', 'y' ] [ 0, 10, 20, 30, 40 ] A-B-C
Array.from({ length: 5 }, (_, i) => i * 10) is a neat trick for creating a numbered list. The underscore _ is a common name for a parameter you don't need (here, the item, which doesn't exist yet). We only care about the index i.
Which method do I need?
| Your question | Method | Returns |
|---|---|---|
| "Do something with each item" | forEach | nothing (undefined) |
| "Change every item" | map | new array, same length |
| "Keep only some items" | filter | new array, maybe shorter |
| "Find the first item that matches" | find | the item, or undefined |
| "Where is the first match?" | findIndex | an index, or -1 |
| "Does any item match?" | some | true / false |
| "Does every item match?" | every | true / false |
| "Combine everything into one value" | reduce | anything |
| "Put them in order" | sort | the same (sorted) array |