JavaScript Array & Object Snippets
Verified logic grids for efficient data manipulation and object handling in modern JavaScript.
Array Manipulation
| Method | Code Snippet | Result / Use Case |
|---|---|---|
| .map() | const doubled = arr.map(x => x * 2); | Creates a new array by transforming every element. |
| .filter() | const active = users.filter(u => u.isActive); | Returns a subset of elements that pass a test. |
| .reduce() | const total = prices.reduce((a, b) => a + b, 0); | Reduces array to a single value (sum, average, etc). |
Object & Spread Logic
| Logic | Code Snippet | Result / Use Case |
|---|---|---|
| Spread (...) | const newObj = { ...oldObj, status: 'done' }; | Clones an object while overriding specific properties. |
| Destructuring | const { name, age } = user; | Extracts properties into clean, standalone variables. |
| Keys / Values | Object.keys(myObj).length; | Efficient way to check object size or iterate keys. |
Immutability Tip: Modern JS frameworks (like React) prefer .map() and .filter() because they return new arrays instead of modifying the original, keeping your data predictable.