Hi Guy’s Welcome to Proto Codes Point, In this TypeScript Tutorial let’s check out Array Manipulation & Methods in TypeScript.
What is Array Manipulation?
In TypeScript Array Manipulation is a technique of performing various operations on arrays to add, remove or update elements of Arrays. This Allows you to change the contents within the array dynamically as required.
Benefits of Array Manipulation
- Allows for dynamic modification of array contents based on changing requirements.
- Provides flexibility in managing data structures & performing operations efficiently.
- Enables Implementation of various algorithms & solving real-world problems effectively.
Array Methods in TypeScript
- push()
- pop()
- shift()
- unshift()
- splice()
- concat()
- slice()
- indexOf()
- includes()
- forEach()
- join()
- reverse()
- filter()
- map()
- find()
- findIndex()
- every()
- some()
- sort()
Method Explanation
push(): Adds one or more elements to the end of an array. Real-life example: Adding items to a shopping cart.
let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.push("Orange", "Grape");
pop(): Removes the last element from an array. Real-life example: Removing the last item from a stack.
let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.pop(); //removes last element i.e.Apple.
shift(): Removes the first element from an array. Real-Life example: Taking the first book from a bookshelf.
let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
let firstItem = shoppingCart.shift(); // Watermelon
unshift(): Adds one or more elements to the beginning of an array. Real-life example: Adding a new books in bookshelf at the starting of the list.
let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.unshift("Grape" , "Orange"); // "Grape", "Orange", "Watermelon" ,"Apple"
splice(): Adds or removes elements from an array at a specific position. Real-life example: Modifying ingredients in a recipe.
Real-life exalet shoppingCart: string[] = [ "flour" ,"sugar"];
shoppingCart.splice(1, 1, "Butter"); // Remove "sugar" and add "Butter".
concat(): Combines two or more arrays and returns a new array.
let fruitGroup1: string[] = [ "Watermelon" ,"Apple"];
let fruitGroup2: string[] = [ "Grape" ,"Orange"];
let AllFruits: string[] = fruitGroup1.concat(fruitGroup2); // "Grape", "Orange", "Watermelon" ,"Apple"
slice(): can be used to selecting a range index from and to from the array and return a new array.
let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let selectedBooks: string[] = fruits.slice(1,3); ["Orange", "Watermelon"]
Select fruits from index 1 to 2 i.e. [“Orange”, “Watermelon”]
indexOf(): This will return the first index at which the given element is found & in case if element is not found the the array we get -1 as responce.
let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let firstPosition: number = fruits.indexOf("Orange"); 1
let firstPosition: number = fruits.indexOf("banana"); // -1, because the element is not the the array list
includes(): check if the element exist in the array or no, return boolean value true or false.
let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let isExist: number = fruits.includes("Orange"); true
let isExist: number = fruits.includes("banana"); false
forEach(): Iterate to each element in the given array.
let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
fruits.forEach(ele=> console.log(ele));
join(): convert all element into a long string, optionally can add symbols like commas(,) to separate them.
let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let joinedFruits: string[] = fruits.join(","); // "Grape, Orange, Watermelon, Apple"
reverse(): Reverses the order of the element in an array.
let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
fruits.reverse(); //[ "Apple", "Watermelon" , "Orange", "Grape" ]
filter(): This is used to filter element with a specific condition, if the condition pass the test a new fresh array will be return as per filter login.
// Define an array of numbers
const numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Use the filter method to get even numbers
const evenNumbers: number[] = numbers.filter(num => num % 2 === 0);
console.log("Original array:", numbers); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log("Even numbers:", evenNumbers); [2, 4, 6, 8, 10]
map(): The map
method in TypeScript is used to iterate each element of an given array & create a new array as per required condition or login. Here’s an example: Below I am just iterating array using map and getting uppercase array in return.
// Define an array of strings
const fruits: string[] = ["apple", "banana", "orange", "grape", "kiwi"];
// Use the map method to create a new array of uppercase fruits
const uppercaseFruits: string[] = fruits.map(fruit => fruit.toUpperCase());
console.log("Uppercase fruits:", uppercaseFruits); ["APPLE", "BANANA", "ORANGE", "GRAPE", "KIWI"]
find(): This is similar to indexOf but not same, Here in find
method of TypeScript is used to retrieve the first element in an array that satisfies a given condition. Here’s an example:
// Define an array of objects representing persons
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 },
{ name: "David", age: 35 },
];
// Use the find method to get the first person older than 30
const olderThan30: Person | undefined = people.find(person => person.age > 30);
console.log("People array:", people);
console.log("First person older than 30:", olderThan30);
findIndex(): The findIndex
method in TypeScript is similar to find
, but instead of returning the element itself, it returns the index of the first element in an array that satisfies a given condition.
// Define an array of objects representing persons
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 },
{ name: "David", age: 35 },
];
// Use the find method to get the first person index value older than 30:
const olderThan30: Person | undefined = people.find(person => person.age > 30);
console.log("People array:", people);
console.log("First person older than 30 it index is :", olderThan30); // 3
every(): The every
method in TypeScript is used to check if all elements in an array satisfy a given condition. It returns a boolean value. Here’s an example:
// Define an array of numbers
const numbers: number[] = [2, 4, 6, 8, 10];
// Use the every method to check if all numbers are even
const allEven: boolean = numbers.every(num => num % 2 === 0);
console.log("Numbers array:", numbers);
console.log("Are all numbers even?", allEven);
some(): The some
method in TypeScript is used to check if at least one element in an array satisfies a given condition. It returns a boolean value. Here’s an example:
// Define an array of numbers
const numbers: number[] = [1, 3, 5, 7, 9, 10];
// Use the some method to check if at least one number is even
const hasEvenNumber: boolean = numbers.some(num => num % 2 === 0);
console.log("Numbers array:", numbers);
console.log("Does the array contain at least one even number?", hasEvenNumber);
sort(): The sort
method in TypeScript is used to sort the elements of an array. By default, it sorts the elements as strings, but you can provide a custom comparison function to define the sorting order. Here’s an example:
// Define an array of strings
const fruits: string[] = ["banana", "apple", "orange", "kiwi", "grape"];
// Use the sort method to sort the array alphabetically
const sortedFruitsAlphabetical: string[] = fruits.slice().sort();
console.log("Original array:", fruits);
console.log("Sorted array (alphabetical):", sortedFruitsAlphabetical);
// Use the sort method with a custom comparison function to sort by length
const sortedFruitsByLength: string[] = fruits.slice().sort((a, b) => a.length - b.length);
console.log("Sorted array (by length):", sortedFruitsByLength);
In the first part of the example, the sort
method is used without any arguments to sort the fruits
array alphabetically. Keep in mind that sort
modifies the original array, so it’s a good practice to create a copy using slice()
before sorting.
In the second part, a custom comparison function is provided to the sort
method, sorting the array based on the length of the strings. The comparison function takes two elements, a
and b
, and returns a negative value if a
should come before b
, a positive value if a
should come after b
, or zero if they are equal.
Conclusion
Array manipulation involves performing operations like adding, removing or modifying elements within the arrays. Understanding array manipulation is very much essential for building applications that involving playing with data or processing the list of datas.