Array Methods in TypeScript
Learn how to add, remove, search, filter, transform, and process array elements using built-in array methods in TypeScript.
What Are Array Methods?
Array methods are functions available on JavaScript arrays. TypeScript supports these methods and checks their usage according to the array's element types.
- Add or remove elements from an array.
- Transform elements into a new array.
- Select elements that match a condition.
- Search for a particular element.
- Calculate a result by processing all elements.
Array Methods Workflow
Follow these steps to understand how an array method processes data.
Step 1
Create ArrayStore the initial values.
Step 2
Apply MethodChoose the required array operation.
Step 3
Process ElementsModify, search, or transform values.
Step 4
Get ResultReceive the updated array or result.
Visual Example: Map Method
[1, 2, 3]
Multiply each number by 2.
[2, 4, 6]
1. Push and Pop Methods
The push and pop methods add or remove elements at the end of an array.
A. Push Method
The push() method adds one or more
elements to the end of an array and returns
the new array length.
let courses: string[] = ["Java", "Python"];
courses.push(".NET");
console.log(courses);
Expected Output
[ 'Java', 'Python', '.NET' ]
B. Pop Method
The pop() method removes the last
element from an array and returns the removed value.
let courses: string[] = ["Java", "Python", ".NET"];
let removedCourse: string | undefined = courses.pop();
console.log("Removed Course:", removedCourse);
console.log("Remaining Courses:", courses);
Expected Output
Removed Course: .NET
Remaining Courses: [ 'Java', 'Python' ]
Explanation
-
push()adds elements at the end. -
pop()removes the last element.
2. Unshift and Shift Methods
The unshift and shift methods add or remove elements at the beginning of an array.
A. Unshift Method
let numbers: number[] = [20, 30, 40];
numbers.unshift(10);
console.log(numbers);
Expected Output
[ 10, 20, 30, 40 ]
B. Shift Method
let numbers: number[] = [10, 20, 30, 40];
let removedNumber: number | undefined = numbers.shift();
console.log("Removed Number:", removedNumber);
console.log("Remaining Numbers:", numbers);
Expected Output
Removed Number: 10
Remaining Numbers: [ 20, 30, 40 ]
Explanation
-
unshift()inserts elements at the beginning. -
shift()removes the first element.
3. Map Method
The map() method calls a function for
every element and returns a new array containing
the transformed values. It does not modify the
original array by itself.
Example
let numbers: number[] = [1, 2, 3, 4, 5];
let doubledNumbers: number[] = numbers.map(
(number: number): number => number * 2
);
console.log("Original Array:", numbers);
console.log("Doubled Array:", doubledNumbers);
Expected Output
Original Array: [ 1, 2, 3, 4, 5 ]
Doubled Array: [ 2, 4, 6, 8, 10 ]
Explanation
- Each array element is passed to the callback function.
- The callback multiplies the number by 2.
- The returned values are collected into a new array.
4. Filter Method
The filter() method creates a new array
containing only the elements that satisfy a condition.
Example
let marks: number[] = [35, 60, 75, 25, 90];
let passedMarks: number[] = marks.filter(
(mark: number): boolean => mark >= 40
);
console.log("All Marks:", marks);
console.log("Passed Marks:", passedMarks);
Expected Output
All Marks: [ 35, 60, 75, 25, 90 ]
Passed Marks: [ 60, 75, 90 ]
Explanation
Only marks greater than or equal to 40 satisfy the condition. The other values are excluded from the returned array.
5. Find and FindIndex Methods
The find() method returns the first
element that matches a condition. The
findIndex() method returns the index
of the first matching element.
Example
let numbers: number[] = [10, 20, 30, 40, 50];
let foundNumber: number | undefined = numbers.find(
(number: number): boolean => number > 25
);
let foundIndex: number = numbers.findIndex(
(number: number): boolean => number > 25
);
console.log("Found Number:", foundNumber);
console.log("Found Index:", foundIndex);
Expected Output
Found Number: 30
Found Index: 2
Explanation
- The first number greater than 25 is 30.
- The index of 30 is 2.
-
If no element matches,
find()returns undefined andfindIndex()returns -1.
6. ForEach Method
The forEach() method executes a
callback function for each element of an array.
It is useful when we want to perform an action
for every element.
Example
let courses: string[] = [
"Java",
"Python",
".NET"
];
courses.forEach((course: string): void => {
console.log("Course:", course);
});
Expected Output
Course: Java
Course: Python
Course: .NET
Explanation
The callback executes once for each course.
Unlike map(), forEach()
is primarily used for side effects and returns
undefined rather than a new transformed array.
7. Reduce Method
The reduce() method processes array
elements to produce a single accumulated result,
such as a sum or total.
Example
let numbers: number[] = [10, 20, 30, 40];
let total: number = numbers.reduce(
(sum: number, number: number): number => sum + number,
0
);
console.log("Total:", total);
Expected Output
Total: 100
How Reduce Works
| Current Number | Previous Total | New Total |
|---|---|---|
| 10 | 0 | 10 |
| 20 | 10 | 30 |
| 30 | 30 | 60 |
| 40 | 60 | 100 |
The initial accumulator value is 0. Each iteration adds the current number to the accumulated total.
8. Slice Method
The slice() method returns a shallow
copy of a selected portion of an array without
modifying the original array.
Example
let numbers: number[] = [10, 20, 30, 40, 50];
let selectedNumbers: number[] = numbers.slice(1, 4);
console.log("Original Array:", numbers);
console.log("Selected Values:", selectedNumbers);
Expected Output
Original Array: [ 10, 20, 30, 40, 50 ]
Selected Values: [ 20, 30, 40 ]
Explanation
The first argument is the starting index, which is
included. The second argument is the ending index,
which is excluded. Therefore, slice(1, 4)
returns the elements at indexes 1, 2, and 3.
9. Splice Method
The splice() method changes the original
array by removing, replacing, or inserting elements.
Example: Remove an Element
let courses: string[] = [
"Java",
"Python",
".NET",
"React"
];
let removedCourses: string[] = courses.splice(1, 1);
console.log("Removed:", removedCourses);
console.log("Remaining:", courses);
Expected Output
Removed: [ 'Python' ]
Remaining: [ 'Java', '.NET', 'React' ]
Example: Insert an Element
let courses: string[] = ["Java", ".NET"];
courses.splice(1, 0, "Python");
console.log(courses);
Expected Output
[ 'Java', 'Python', '.NET' ]
Unlike slice(), splice()
modifies the original array.
10. Includes and IndexOf Methods
The includes() method checks whether
an array contains a value. The indexOf()
method returns the first index of a matching value.
Example
let courses: string[] = [
"Java",
"Python",
".NET"
];
console.log(courses.includes("Python"));
console.log(courses.includes("React"));
console.log(courses.indexOf(".NET"));
console.log(courses.indexOf("React"));
Expected Output
true
false
2
-1
Explanation
-
includes()returns true when the value is found and false otherwise. -
indexOf()returns -1 when the value is not found.
11. Sort and Reverse Methods
The sort() method sorts array elements,
while reverse() reverses their order.
Both methods modify the original array.
Example: Numeric Sorting
let numbers: number[] = [40, 10, 30, 20, 5];
numbers.sort(
(a: number, b: number): number => a - b
);
console.log("Ascending:", numbers);
numbers.reverse();
console.log("Descending:", numbers);
Expected Output
Ascending: [ 5, 10, 20, 30, 40 ]
Descending: [ 40, 30, 20, 10, 5 ]
Important Point
By default, JavaScript sorts array elements as strings.
For numeric ascending order, use a comparison function
such as (a, b) => a - b.
12. Array Methods Comparison
| Method | Purpose | Modifies Original Array? |
|---|---|---|
push() |
Adds elements at the end. | Yes |
pop() |
Removes the last element. | Yes |
shift() |
Removes the first element. | Yes |
unshift() |
Adds elements at the beginning. | Yes |
map() |
Transforms each element into a new array. | No, not by itself |
filter() |
Selects matching elements into a new array. | No, not by itself |
find() |
Returns the first matching element. | No, not by itself |
reduce() |
Combines elements into an accumulated result. | No, not by itself |
slice() |
Returns a selected portion of an array. | No |
splice() |
Inserts, removes, or replaces elements. | Yes |
sort() |
Sorts array elements. | Yes |
reverse() |
Reverses element order. | Yes |
13. Practical Example: CIIT Student Results
Let's use array methods to process student marks, select passing students' marks, and calculate their total and average.
Example
let marks: number[] = [35, 75, 80, 25, 90, 60];
let passedMarks: number[] = marks.filter(
(mark: number): boolean => mark >= 40
);
let totalMarks: number = passedMarks.reduce(
(total: number, mark: number): number => total + mark,
0
);
let averageMarks: number =
totalMarks / passedMarks.length;
console.log("All Marks:", marks);
console.log("Passed Marks:", passedMarks);
console.log("Total Passed Marks:", totalMarks);
console.log("Average Passed Marks:", averageMarks);
Expected Output
All Marks: [ 35, 75, 80, 25, 90, 60 ]
Passed Marks: [ 75, 80, 90, 60 ]
Total Passed Marks: 305
Average Passed Marks: 76.25
Explanation
-
filter()selects marks greater than or equal to 40. -
reduce()calculates the total of the passing marks. - The average is calculated by dividing the total by the number of passing marks.
Common Mistakes
-
Assuming that
map()modifies the original array. -
Confusing
slice()withsplice(). -
Forgetting that
find()may return undefined when no element matches. -
Forgetting the initial accumulator value when
using
reduce(). - Sorting numbers without a numeric comparison function.
- Calculating an average without handling an empty array.
Practice Task
Write TypeScript programs to complete the following tasks.
- Use push and pop to add and remove course names.
- Use map to square every number in an array.
- Use filter to select marks greater than or equal to 60.
- Use find to locate the first number greater than 50.
- Use reduce to calculate the total of an array of prices.
- Use slice and splice to compare copying and modifying arrays.
- Sort an array of numbers in ascending and descending order.
Summary
In this lesson, we learned how to use common array methods such as push, pop, shift, unshift, map, filter, find, findIndex, forEach, reduce, slice, splice, includes, indexOf, sort, and reverse. These methods help us update, search, transform, and process array data in TypeScript.