Arrays are everywhere in test automation — storing test data, collecting page elements, managing results. TypeScript arrays come with strong typing that catches bugs before your tests even run. This guide covers everything from basics to advanced patterns with Playwright examples.
📖 What You’ll Learn: Array types, push/pop/splice, map/filter/reduce, spread operator, tuples, readonly arrays, and array operations in Playwright tests.
📦 Declaring Arrays
// Two ways to declare typed arrays
let browsers: string[] = ['chromium', 'firefox', 'webkit'];
let scores: Array<number> = [85, 92, 78, 95];
// Mixed types with union
let mixed: (string | number)[] = ['hello', 42, 'world'];
// Empty array with type
let results: boolean[] = [];
// Array of objects
let users: { name: string; role: string }[] = [
{ name: 'Deepesh', role: 'SDET' },
{ name: 'John', role: 'QA Lead' },
];
// 2D array (matrix)
let grid: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
➕ Adding & Removing Elements
let fruits: string[] = ['apple', 'banana'];
// Add to end
fruits.push('cherry'); // ['apple', 'banana', 'cherry']
// Add to beginning
fruits.unshift('mango'); // ['mango', 'apple', 'banana', 'cherry']
// Remove from end
let last = fruits.pop(); // 'cherry', array: ['mango', 'apple', 'banana']
// Remove from beginning
let first = fruits.shift(); // 'mango', array: ['apple', 'banana']
// Remove/insert at position with splice
let colors: string[] = ['red', 'green', 'blue', 'yellow'];
colors.splice(1, 2); // Remove 2 items from index 1 → ['red', 'yellow']
colors.splice(1, 0, 'purple'); // Insert at index 1 → ['red', 'purple', 'yellow']
// Find index and remove
let items = ['a', 'b', 'c', 'd'];
let idx = items.indexOf('c');
if (idx !== -1) items.splice(idx, 1); // ['a', 'b', 'd']
🔍 Searching & Checking Arrays
let numbers: number[] = [10, 20, 30, 40, 50];
// includes — does it contain a value?
console.log(numbers.includes(30)); // true
// indexOf — find position (-1 if not found)
console.log(numbers.indexOf(40)); // 3
// find — first element matching condition
let found = numbers.find(n => n > 25);
console.log(found); // 30
// findIndex — index of first match
let foundIdx = numbers.findIndex(n => n > 25);
console.log(foundIdx); // 2
// every — do ALL elements match?
let allPositive = numbers.every(n => n > 0); // true
// some — does ANY element match?
let hasLarge = numbers.some(n => n > 100); // false
🔄 map, filter & reduce
let prices: number[] = [100, 200, 300, 400, 500];
// map — transform each element
let discounted = prices.map(p => p * 0.9);
console.log(discounted); // [90, 180, 270, 360, 450]
// filter — keep elements matching condition
let expensive = prices.filter(p => p >= 300);
console.log(expensive); // [300, 400, 500]
// reduce — combine all elements into one value
let total = prices.reduce((sum, p) => sum + p, 0);
console.log(total); // 1500
// Chaining — filter + map + reduce
let premiumTotal = prices
.filter(p => p >= 300) // [300, 400, 500]
.map(p => p * 1.1) // [330, 440, 550]
.reduce((sum, p) => sum + p, 0); // 1320
console.log(premiumTotal);
// flat — flatten nested arrays
let nested: number[][] = [[1, 2], [3, 4], [5]];
let flat = nested.flat();
console.log(flat); // [1, 2, 3, 4, 5]
💡 map transforms, filter selects, reduce combines. Chain them together for powerful data pipelines. These are the three most important array methods to master.
📌 Spread, Destructuring & Tuples
// Spread operator — copy and merge arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
let copy = [...arr1]; // [1, 2, 3] — independent copy
// Destructuring — extract values
let [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first); // 10
console.log(rest); // [30, 40, 50]
// Tuple — fixed-length, typed array
let coord: [number, number] = [40.7128, -74.0060];
let entry: [string, number, boolean] = ['test-1', 95, true];
// Readonly array — cannot be modified
const readonlyBrowsers: readonly string[] = ['chromium', 'firefox', 'webkit'];
// readonlyBrowsers.push('edge'); // ❌ Error! Cannot modify
// Sorting
let nums = [30, 10, 50, 20, 40];
nums.sort((a, b) => a - b); // [10, 20, 30, 40, 50] ascending
nums.sort((a, b) => b - a); // [50, 40, 30, 20, 10] descending
🎭 Arrays in Playwright — Real Examples
import { test, expect } from '@playwright/test';
test('collect and verify all product names', async ({ page }) => {
await page.goto('https://sqatools.in');
// Collect all text content into an array
const links = page.locator('nav a');
const texts: string[] = await links.allTextContents();
console.log('Navigation links:', texts);
expect(texts.length).toBeGreaterThan(0);
// Filter only links containing 'Playwright'
const playwrightLinks = texts.filter(t => t.toLowerCase().includes('playwright'));
console.log('Playwright links:', playwrightLinks);
});
// Data-driven testing with arrays
const testData: [string, string, boolean][] = [
['admin@test.com', 'admin123', true],
['invalid@test.com', 'wrong', false],
['', '', false],
];
for (const [email, password, shouldPass] of testData) {
test(`login with ${email || 'empty'} should ${shouldPass ? 'pass' : 'fail'}`, async ({ page }) => {
await page.goto('/login');
await page.fill('#email', email);
await page.fill('#password', password);
await page.click('#submit');
if (shouldPass) {
await expect(page.locator('.dashboard')).toBeVisible();
} else {
await expect(page.locator('.error')).toBeVisible();
}
});
}
❓ FAQ
🤔 What is the difference between string[] and Array<string>?
They are identical — both declare an array of strings. string[] is shorter and more commonly used. Array<string> is clearer for complex types like Array<Map<string, number>>.
🤔 How do I get all text from Playwright locators into an array?
Use await locator.allTextContents() — it returns a string[] with the text content of every matching element. For inner text, use allInnerTexts().
🎯 Next Steps
- 📘 TypeScript Operators
- 📘 TypeScript Loops
- 📘 TypeScript Functions
- 📘 TypeScript Objects — Coming next!
- 🎬 SqaToolsByDY on YouTube
🎬 Watch the full TypeScript tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in