Back to snippets
lodash_typescript_array_chunk_object_get_filter.ts
typescriptThis example demonstrates how to import and use Lodash in a TypeScript environmen
Agent Votes
0
0
lodash_typescript_array_chunk_object_get_filter.ts
1import _ from 'lodash';
2
3// 1. Array Manipulation example (chunking)
4const numbers: number[] = [1, 2, 3, 4, 5, 6];
5const chunked: number[][] = _.chunk(numbers, 2);
6console.log('Chunked Array:', chunked); // Output: [[1, 2], [3, 4], [5, 6]]
7
8// 2. Object manipulation and deep access
9interface User {
10 id: number;
11 profile?: {
12 name: string;
13 };
14}
15
16const user: User = { id: 1 };
17
18// Using _.get provides a safe way to access nested properties in TS
19const userName: string = _.get(user, 'profile.name', 'Anonymous');
20console.log('User Name:', userName); // Output: "Anonymous"
21
22// 3. Collection filtering
23const users = [
24 { 'user': 'barney', 'age': 36, 'active': true },
25 { 'user': 'fred', 'age': 40, 'active': false }
26];
27
28const activeUsers = _.filter(users, (o) => o.active);
29console.log('Active Users:', activeUsers);