Arrays:
Arrays are the most basic and widely used data structure in JavaScript/TypeScript. They are used to store a collection of elements, which can be of any type.
let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ['apple', 'banana', 'orange'];
let mixed: (number | string)[] = [1, 'hello', 3, 'world'];
Objects:
JavaScript objects are key-value pairs and can be used to create collections of related data.
let person: { name: string; age: number } = { name: 'John', age: 30 };
Maps:
In JavaScript/TypeScript, the Map class provides a more versatile way to create collections with key-value pairs.
let myMap = new Map<number, string>();
myMap.set(1, 'One');
myMap.set(2, 'Two');
console.log(myMap.get(1));
Sets:
The Set class is used to store unique values of any type, meaning duplicate values are automatically removed.
let mySet = new Set<number>();
mySet.add(1);
mySet.add(2);
mySet.add(1);
console.log(mySet);
Third-Party Libraries:
To use more advanced data structures and utilities, you can consider third-party libraries like "lodash" or "immutable.js". These libraries provide additional collections and utility functions that can be beneficial in certain scenarios.
Example using lodash:
import * as _ from 'lodash';
let numbers: number[] = [1, 2, 3, 4, 5];
let sum: number = _.sum(numbers);
console.log(sum);