Typescript : Arrays
How do you add an element to an array?
const companies: string[] = ["Apple", "Amazon", "Meta", "Google"];
Let's say we want to add "Microsoft" to the above array. We can use the push() method which adds a new item to the end of the array.
companies.push("Microsoft");
How do you check whether an array is empty or not?
if (companies?.length) {
console.log("Array is empty");
}
How do you find an element in the array?
We use the find() method to return the value of the first element in the array that matches the condition. Let's say we want to find the first value greater than 10 in the below array.
const numbers = [3, 5, 7, 9, 12, 13];
let x = numbers.find(num => num > 10);
Output: x = 12
How do you check an element's presence in the array?
Let's say we want to check whether the number 15 is present in above array or not.
let isNumberPresent = numbers.some(num => num === 15);
Output: isNumberPresent = false
How do you convert an array into another array?
Let's say we need a new array where the value of every element is multiplied by 10. We can use the map() function.
const multipliedNumbers = numbers.map(num => num * 10);
Output: [30, 50, 70, 90, 120, 130]