Scenario-Based JavaScript Array Programs

Below is a collection of real-world, scenario-based JavaScript array programs designed for QA/SDET training, coding practice, and interviews. They progress from beginner to advanced.


1. Find the Highest Product Price

Scenario

An e-commerce application stores product prices. Find the most expensive product.

const prices = [1200, 4500, 2300, 8900, 1500];

let maxPrice = prices[0];

for (let price of prices) {
    if (price > maxPrice) {
        maxPrice = price;
    }
}

console.log("Highest Price:", maxPrice);

Expected Output:

Highest Price: 8900

2. Find the Lowest Product Price

const prices = [1200, 4500, 2300, 8900, 1500];

let minPrice = prices[0];

for (let price of prices) {
    if (price < minPrice) {
        minPrice = price;
    }
}

console.log("Lowest Price:", minPrice);

3. Calculate Total Shopping Cart Amount

Scenario

A shopping cart contains multiple product prices. Calculate the total.

const cart = [499, 1299, 799, 2499];

let total = 0;

for (let price of cart) {
    total += price;
}

console.log("Cart Total:", total);

Output:

Cart Total: 5096

4. Find Products Above ₹1000

const prices = [500, 1200, 2500, 700, 1800, 450];

const result = [];

for (let price of prices) {
    if (price > 1000) {
        result.push(price);
    }
}

console.log(result);

Output:

[1200, 2500, 1800]

5. Remove Duplicate Product IDs

Scenario

During automation testing, duplicate product IDs are received from an API.

const productIds = [101, 102, 103, 101, 104, 102, 105];

const uniqueIds = [];

for (let id of productIds) {
    if (!uniqueIds.includes(id)) {
        uniqueIds.push(id);
    }
}

console.log(uniqueIds);

Output:

[101, 102, 103, 104, 105]

6. Find Duplicate Values

const ids = [101, 102, 103, 101, 104, 102, 105];

const duplicates = [];

for (let i = 0; i < ids.length; i++) {
    for (let j = i + 1; j < ids.length; j++) {

        if (ids[i] === ids[j] && !duplicates.includes(ids[i])) {
            duplicates.push(ids[i]);
        }
    }
}

console.log("Duplicates:", duplicates);

Output:

Duplicates: [101, 102]

7. Find Second Highest Salary

Scenario

An HR application stores employee salaries. Find the second-highest salary without sorting.

const salaries = [45000, 75000, 55000, 90000, 65000];

let highest = -Infinity;
let secondHighest = -Infinity;

for (let salary of salaries) {

    if (salary > highest) {
        secondHighest = highest;
        highest = salary;
    } 
    else if (salary > secondHighest && salary !== highest) {
        secondHighest = salary;
    }
}

console.log("Highest:", highest);
console.log("Second Highest:", secondHighest);

Output:

Highest: 90000
Second Highest: 75000

8. Count Passed and Failed Students

Scenario

A training institute stores student marks. Determine how many students passed.

const marks = [85, 45, 72, 30, 90, 55, 28];

let passed = 0;
let failed = 0;

for (let mark of marks) {

    if (mark >= 40) {
        passed++;
    } else {
        failed++;
    }
}

console.log("Passed:", passed);
console.log("Failed:", failed);

9. Calculate Average Marks

const marks = [80, 75, 90, 65, 85];

let total = 0;

for (let mark of marks) {
    total += mark;
}

const average = total / marks.length;

console.log("Average:", average);

10. Find Students Who Scored Above Average

const marks = [80, 45, 90, 65, 85];

let total = 0;

for (let mark of marks) {
    total += mark;
}

const average = total / marks.length;

const aboveAverage = [];

for (let mark of marks) {
    if (mark > average) {
        aboveAverage.push(mark);
    }
}

console.log("Average:", average);
console.log("Above Average:", aboveAverage);

11. Find Missing Test Case IDs

Scenario

A QA automation suite should execute test cases from 1 to 10, but some test cases are missing.

const executedTests = [1, 2, 3, 5, 6, 8, 10];

const missingTests = [];

for (let i = 1; i <= 10; i++) {

    if (!executedTests.includes(i)) {
        missingTests.push(i);
    }
}

console.log("Missing Tests:", missingTests);

Output:

Missing Tests: [4, 7, 9]

12. Count Even and Odd Numbers

Scenario

An application receives transaction IDs and needs to classify them.

const transactionIds = [101, 202, 303, 404, 505, 606];

let even = 0;
let odd = 0;

for (let id of transactionIds) {

    if (id % 2 === 0) {
        even++;
    } else {
        odd++;
    }
}

console.log("Even:", even);
console.log("Odd:", odd);

13. Reverse an Array Without reverse()

const users = ["John", "David", "Mike", "Alex"];

const reversed = [];

for (let i = users.length - 1; i >= 0; i--) {
    reversed.push(users[i]);
}

console.log(reversed);

Output:

["Alex", "Mike", "David", "John"]

14. Find a Specific User

const users = ["John", "David", "Mike", "Alex"];

const searchUser = "Mike";

if (users.includes(searchUser)) {
    console.log("User Found");
} else {
    console.log("User Not Found");
}

15. Count Occurrence of a Value

Scenario

Find how many times a particular product was purchased.

const products = [
    "Laptop",
    "Mobile",
    "Laptop",
    "Tablet",
    "Laptop",
    "Mobile"
];

const searchProduct = "Laptop";

let count = 0;

for (let product of products) {
    if (product === searchProduct) {
        count++;
    }
}

console.log("Laptop purchased:", count, "times");

16. Find Common Elements Between Two Arrays

Scenario

Find users who are present in both applications.

const app1Users = ["John", "David", "Mike", "Alex"];
const app2Users = ["Mike", "Alex", "Robert", "Sam"];

const commonUsers = [];

for (let user of app1Users) {

    if (app2Users.includes(user)) {
        commonUsers.push(user);
    }
}

console.log(commonUsers);

Output:

["Mike", "Alex"]

17. Find Unique Elements From Two Arrays

const teamA = ["John", "David", "Mike"];
const teamB = ["Mike", "Alex", "David"];

const result = [];

for (let user of [...teamA, ...teamB]) {

    if (!result.includes(user)) {
        result.push(user);
    }
}

console.log(result);

18. Find Failed Test Cases

Scenario

A Playwright test execution produces test statuses.

const statuses = [
    "passed",
    "failed",
    "passed",
    "skipped",
    "failed",
    "passed"
];

const failedTests = [];

for (let status of statuses) {

    if (status === "failed") {
        failedTests.push(status);
    }
}

console.log("Failed Tests:", failedTests.length);

19. Separate Positive and Negative Numbers

const numbers = [10, -5, 20, -8, 15, -2];

const positive = [];
const negative = [];

for (let number of numbers) {

    if (number >= 0) {
        positive.push(number);
    } else {
        negative.push(number);
    }
}

console.log("Positive:", positive);
console.log("Negative:", negative);

20. Move All Zeros to the End

Scenario

An API returns an array containing zero values. Move all zero values to the end.

const numbers = [0, 5, 0, 3, 8, 0, 2];

const result = [];

let zeroCount = 0;

for (let number of numbers) {

    if (number === 0) {
        zeroCount++;
    } else {
        result.push(number);
    }
}

for (let i = 0; i < zeroCount; i++) {
    result.push(0);
}

console.log(result);

Output:

[5, 3, 8, 2, 0, 0, 0]

21. Find First Non-Repeated Element

Scenario

Find the first unique transaction ID.

const ids = [101, 102, 101, 103, 102, 104];

for (let id of ids) {

    let count = 0;

    for (let value of ids) {

        if (id === value) {
            count++;
        }
    }

    if (count === 1) {
        console.log("First non-repeated ID:", id);
        break;
    }
}

Output:

First non-repeated ID: 103

22. Find Maximum Consecutive Number

const numbers = [10, 20, 30, 25, 50, 60];

let maxDifference = 0;
let firstNumber;
let secondNumber;

for (let i = 0; i < numbers.length - 1; i++) {

    const difference = numbers[i + 1] - numbers[i];

    if (difference > maxDifference) {
        maxDifference = difference;
        firstNumber = numbers[i];
        secondNumber = numbers[i + 1];
    }
}

console.log(firstNumber, secondNumber);

23. Pagination Scenario

Scenario

An API returns 50 records. Display records for page 3 where each page contains 10 records.

const users = Array.from({ length: 50 }, (_, i) => `User-${i + 1}`);

const page = 3;
const pageSize = 10;

const startIndex = (page - 1) * pageSize;

const pageData = users.slice(
    startIndex,
    startIndex + pageSize
);

console.log(pageData);

Output:

[
 "User-21",
 "User-22",
 ...
 "User-30"
]

24. Search Products by Keyword

const products = [
    "iPhone 15",
    "Samsung Galaxy",
    "MacBook Pro",
    "iPad Air",
    "Samsung TV"
];

const keyword = "Samsung";

const result = products.filter(product =>
    product.toLowerCase().includes(keyword.toLowerCase())
);

console.log(result);

25. Apply Discount to Product Prices

Scenario

Apply a 10% discount to all products.

const prices = [1000, 2500, 5000, 7500];

const discountedPrices = prices.map(price => {
    return price - (price * 10 / 100);
});

console.log(discountedPrices);

Output:

[900, 2250, 4500, 6750]

26. Find Products Within a Price Range

const prices = [500, 1200, 2500, 3500, 4500, 6000];

const min = 1000;
const max = 4000;

const result = prices.filter(price =>
    price >= min && price <= max
);

console.log(result);

Output:

[1200, 2500, 3500]

27. Find the Most Frequent Element

Scenario

Find the product that appears most frequently in orders.

const products = [
    "Laptop",
    "Mobile",
    "Laptop",
    "Tablet",
    "Mobile",
    "Laptop"
];

let maxCount = 0;
let mostFrequent;

for (let product of products) {

    let count = 0;

    for (let value of products) {
        if (product === value) {
            count++;
        }
    }

    if (count > maxCount) {
        maxCount = count;
        mostFrequent = product;
    }
}

console.log("Most Frequent:", mostFrequent);
console.log("Count:", maxCount);

28. Compare Expected and Actual Results

Scenario

This is especially useful for API/UI automation validation.

const expected = ["Login", "Dashboard", "Logout"];
const actual = ["Login", "Dashboard", "Logout"];

let isMatching = true;

if (expected.length !== actual.length) {
    isMatching = false;
} else {

    for (let i = 0; i < expected.length; i++) {

        if (expected[i] !== actual[i]) {
            isMatching = false;
            break;
        }
    }
}

console.log("Result:", isMatching);

29. Find Missing Values Between Two Arrays

const expected = [101, 102, 103, 104, 105];
const actual = [101, 103, 105];

const missing = [];

for (let id of expected) {

    if (!actual.includes(id)) {
        missing.push(id);
    }
}

console.log("Missing:", missing);

Output:

Missing: [102, 104]

30. Flatten Nested Array

Scenario

An API returns nested categories.

const categories = [
    ["Electronics", "Mobile"],
    ["Furniture", "Chair"],
    ["Books", "Novel"]
];

const result = categories.flat();

console.log(result);

Output:

[
    "Electronics",
    "Mobile",
    "Furniture",
    "Chair",
    "Books",
    "Novel"
]

31. QA/SDET Scenario: Validate API Response IDs

const apiResponse = [
    { id: 101, name: "John" },
    { id: 102, name: "David" },
    { id: 103, name: "Mike" }
];

const ids = apiResponse.map(user => user.id);

const expectedIds = [101, 102, 103];

console.log(
    JSON.stringify(ids) === JSON.stringify(expectedIds)
        ? "Test Passed"
        : "Test Failed"
);

32. QA/SDET Scenario: Find Failed Test Names

const testResults = [
    { name: "Login Test", status: "passed" },
    { name: "Search Test", status: "failed" },
    { name: "Checkout Test", status: "passed" },
    { name: "Payment Test", status: "failed" }
];

const failedTests = testResults
    .filter(test => test.status === "failed")
    .map(test => test.name);

console.log(failedTests);

Output:

["Search Test", "Payment Test"]

33. QA/SDET Scenario: Calculate Test Execution Summary

const results = [
    "passed",
    "passed",
    "failed",
    "skipped",
    "passed",
    "failed",
    "passed"
];

const summary = {
    passed: 0,
    failed: 0,
    skipped: 0
};

for (let result of results) {
    summary[result]++;
}

console.log(summary);

Output:

{
    passed: 4,
    failed: 2,
    skipped: 1
}

34. Find Duplicate Test Case IDs

const testCases = [
    "TC001",
    "TC002",
    "TC003",
    "TC001",
    "TC004",
    "TC002"
];

const duplicates = [];

for (let i = 0; i < testCases.length; i++) {

    for (let j = i + 1; j < testCases.length; j++) {

        if (
            testCases[i] === testCases[j] &&
            !duplicates.includes(testCases[i])
        ) {
            duplicates.push(testCases[i]);
        }
    }
}

console.log("Duplicate Test Cases:", duplicates);

Output:

Duplicate Test Cases: ["TC001", "TC002"]

35. Advanced Interview Scenario: Find Two Numbers Whose Sum Equals Target

Scenario

Find two product prices whose total is ₹3000.

const prices = [500, 1200, 1800, 2500, 1500];

const target = 3000;

for (let i = 0; i < prices.length; i++) {

    for (let j = i + 1; j < prices.length; j++) {

        if (prices[i] + prices[j] === target) {
            console.log(
                prices[i],
                "+",
                prices[j],
                "=",
                target
            );
        }
    }
}

Output:

1200 + 1800 = 3000
1500 + 1500 = 3000

Interview Practice Set

For your JavaScript/Playwright/SDET training sessions, these are particularly good interview exercises:

Beginner

  1. Find maximum number.
  2. Find minimum number.
  3. Calculate array sum.
  4. Calculate average.
  5. Count even and odd numbers.
  6. Reverse an array.
  7. Search an element.
  8. Find positive and negative numbers.
  9. Remove duplicates.
  10. Count occurrences.

Intermediate

  1. Find second maximum without sorting.
  2. Find duplicate elements.
  3. Find missing numbers.
  4. Find common elements between arrays.
  5. Find unique elements.
  6. Move zeros to the end.
  7. Find first non-repeated element.
  8. Find most frequent element.
  9. Find elements above average.
  10. Find values within a range.

Advanced

  1. Two-sum problem.
  2. Compare two arrays.
  3. Find array intersection.
  4. Find array difference.
  5. Flatten nested arrays.
  6. Group test results.
  7. Validate API response arrays.
  8. Find duplicate test case IDs.
  9. Implement pagination using arrays.
  10. Process and summarize test execution results.

Leave a Comment