Beyond basic mapping and filtering, JavaScript arrays offer powerful idioms for data transformation. Mastering these patterns reduces the need for external libraries like Lodash.
1. Deduplication with Set
The most idiomatic way to remove duplicates from an array of primitives is using the Set constructor combined with the spread operator.
2. Frequency Counting
You can count occurrences of items in a single pass using reduce. This pattern initializes the accumulator as an empty object.
3. Grouping Data
Grouping objects by a property is a classic use case for reduce. Note: Object.groupBy is a newer standard, but knowing the reduce pattern is essential for compatibility and custom logic.
4. Partitioning
Partitioning splits an array into two arrays based on a condition (e.g., passing vs. failing). This can be done in one pass.