Here are some commonly used array methods in TypeScript for web development, with examples and explanations:
1. map()
- Purpose: Creates a new array with the results of calling a provided function on every element in this array.
- Use case: Transforming data, like converting an array of numbers to strings.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
2. filter()
- Purpose: Creates a new array with all elements that pass the test implemented by the provided function.
- Use case: Filtering out unwanted elements, like selecting only even numbers.
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
3. reduce()
- Purpose: Reduces the array to a single value by executing a provided function for each value of the array from left-to-right.
- Use case: Summing up values, flattening nested arrays, or any accumulation operation.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
4. forEach()
- Purpose: Executes a provided function once for each array element.
- Use case: When you need to perform side effects for each element, like logging or DOM manipulation.
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach(fruit => console.log(fruit));
// Output:
// apple
// banana
// orange
5. find()
- Purpose: Returns the value of the first element in the array that satisfies the provided testing function.
- Use case: Finding a specific element in an array, like finding a user by ID.
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const user = users.find(user => user.id === 2);
console.log(user?.name); // "Bob"
6. some()
- Purpose: Tests whether at least one element in the array passes the test implemented by the provided function.
- Use case: Checking if any item meets a condition, like if there's at least one active user.
const users = [{active: true}, {active: false}, {active: true}];
const hasActiveUser = users.some(user => user.active);
console.log(hasActiveUser); // true
7. every()
- Purpose: Tests whether all elements in the array pass the test implemented by the provided function.
- Use case: Validating that all elements meet a criterion, like all users being of legal age.
const ages = [21, 25, 28];
const allAdults = ages.every(age => age >= 18);
console.log(allAdults); // true
8. concat()
- Purpose: Merges two or more arrays into a new array.
- Use case: Combining lists from different sources, like merging two arrays of items.
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const combined = array1.concat(array2);
console.log(combined); // ['a', 'b', 'c', 'd', 'e', 'f']
9. slice()
-
Purpose: Returns a shallow copy of a portion of an array into a new array object selected from
start
toend
(end not included). - Use case: Extracting a subset of data without modifying the original array.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2, 4)); // ['camel', 'duck']
10. includes()
- Purpose: Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
- Use case: Checking if an array contains a specific value, like checking for membership.
const pets = ['cat', 'dog', 'fish'];
console.log(pets.includes('dog')); // true
console.log(pets.includes('bird')); // false
11. sort()
- Purpose: Sorts the elements of an array in place and returns the reference to the same array, now sorted.
- Use case: Ordering lists, like sorting users by name or age.
const names = ['Bob', 'Alice', 'Charlie'];
names.sort();
console.log(names); // ['Alice', 'Bob', 'Charlie']
These methods are fundamental for manipulating and querying data in arrays, which are central to many programming tasks in web development. TypeScript enhances these methods with type safety, which can prevent common errors by catching type mismatches at compile-time.
Top comments (0)