JavaScript Array Practice Programs with Solutions (33 Programs)

Practise JavaScript arrays with 33 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

Advertisement

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Array Methods lesson first.

JavaScript Beginner Programs

1. Create and read an arrayBeginner

Create an array of three browsers and print the first, last and length.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
console.log(browsers[0]);
console.log(browsers[browsers.length - 1]);
console.log(browsers.length);

Output

chromium
webkit
3

Explanation: array indexes start at 0, so the last item is at length - 1.

2. Add and remove at the endBeginner

Use push and pop on a list of test names.

Show solution
const tests = ['login', 'search'];
tests.push('checkout');
console.log(tests);
const last = tests.pop();
console.log('Removed:', last, '| Now:', tests);

Output

[ 'login', 'search', 'checkout' ]
Removed: checkout | Now: [ 'login', 'search' ]

Explanation: push adds to the end and pop removes and returns the last item.

3. Add and remove at the startBeginner

Use unshift and shift on a queue of jobs.

Show solution
const queue = ['build', 'test'];
queue.unshift('install');
console.log(queue);
const first = queue.shift();
console.log('Processing:', first, '| Remaining:', queue);

Output

[ 'install', 'build', 'test' ]
Processing: install | Remaining: [ 'build', 'test' ]

Explanation: unshift adds to the front and shift removes the first item, which is how a queue works.

4. Check if an item existsBeginner

Check whether 'firefox' and 'edge' are in the browser list.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
console.log(browsers.includes('firefox'));
console.log(browsers.includes('edge'));
console.log(browsers.indexOf('webkit'));

Output

true
false
2

Explanation: includes returns a boolean. indexOf returns the position, or -1 if missing.

5. Double every number with mapBeginner

Double each value in [1, 2, 3, 4].

Show solution
const values = [1, 2, 3, 4];
const doubled = values.map(v => v * 2);
console.log(doubled);
console.log(values);

Output

[ 2, 4, 6, 8 ]
[ 1, 2, 3, 4 ]

Explanation: map returns a new array with each item transformed. The original array is unchanged.

6. Filter even numbersBeginner

Keep only the even numbers from [3, 8, 12, 5, 6].

Show solution
const evens = [3, 8, 12, 5, 6].filter(n => n % 2 === 0);
console.log(evens);

Output

[ 8, 12, 6 ]

Explanation: filter keeps items for which the callback returns true.

7. Sum with reduceBeginner

Add up [120, 80, 45, 55].

Show solution
const total = [120, 80, 45, 55].reduce((sum, n) => sum + n, 0);
console.log(total);

Output

300

Explanation: reduce combines all items into one value, starting from the initial value 0.

8. Join an array into a stringBeginner

Join tags with ', ' and with ' | '.

Show solution
const tags = ['smoke', 'regression', 'api'];
console.log(tags.join(', '));
console.log(tags.join(' | '));

Output

smoke, regression, api
smoke | regression | api

Explanation: join turns an array into a string with your chosen separator.

9. Slice part of an arrayBeginner

Take the first two and the last two items from a list.

Show solution
const steps = ['open', 'login', 'search', 'add to cart', 'checkout'];
console.log(steps.slice(0, 2));
console.log(steps.slice(-2));

Output

[ 'open', 'login' ]
[ 'add to cart', 'checkout' ]

Explanation: slice returns a copy of part of the array without changing the original.

10. Loop with forEachBeginner

Print each item with its index using forEach.

Show solution
const steps = ['open page', 'fill form', 'submit'];
steps.forEach((step, index) => console.log(`${index + 1}. ${step}`));

Output

1. open page
2. fill form
3. submit

Explanation: forEach runs a callback for every item. Use for...of instead when you need await or break.

JavaScript Intermediate Programs

11. Find an itemIntermediate

Find the first user with the role 'admin'.

Show solution
const users = [
  { name: 'Asha', role: 'viewer' },
  { name: 'Ravi', role: 'admin' },
  { name: 'Meera', role: 'admin' }
];
const admin = users.find(u => u.role === 'admin');
console.log(admin.name);
console.log(users.findIndex(u => u.role === 'admin'));

Output

Ravi
1

Explanation: find returns the first matching item and findIndex returns its position.

12. some and everyIntermediate

Check whether some tests failed and whether every test passed.

Show solution
const results = ['passed', 'passed', 'failed'];
console.log('Any failed:', results.some(r => r === 'failed'));
console.log('All passed:', results.every(r => r === 'passed'));

Output

Any failed: true
All passed: false

Explanation: some needs one match, every needs all items to match. Both stop early when the answer is known.

13. Sort numbers correctlyIntermediate

Sort [10, 1, 25, 3] ascending and descending.

Show solution
const values = [10, 1, 25, 3];
console.log([...values].sort());
console.log([...values].sort((a, b) => a - b));
console.log([...values].sort((a, b) => b - a));

Output

[ 1, 10, 25, 3 ]
[ 1, 3, 10, 25 ]
[ 25, 10, 3, 1 ]

Explanation: the default sort compares as strings, so 10 comes before 3. Pass a compare function for numbers. Spreading copies first, because sort changes the array in place.

14. Sort objects by a propertyIntermediate

Sort products by price, then print their names.

Show solution
const products = [
  { name: 'Mouse', price: 599 },
  { name: 'Keyboard', price: 1499 },
  { name: 'Cable', price: 199 }
];
const byPrice = [...products].sort((a, b) => a.price - b.price);
console.log(byPrice.map(p => p.name).join(' < '));

Output

Cable < Mouse < Keyboard

Explanation: the compare function reads the property you want to sort by.

15. Remove duplicatesIntermediate

Remove duplicate tags from ['ui', 'api', 'ui', 'smoke', 'api'].

Show solution
const tags = ['ui', 'api', 'ui', 'smoke', 'api'];
const unique = [...new Set(tags)];
console.log(unique);

Output

[ 'ui', 'api', 'smoke' ]

Explanation: a Set keeps only unique values. Spreading it back gives an array.

16. Flatten nested arraysIntermediate

Flatten [[1, 2], [3, [4, 5]]] one level and fully.

Show solution
const nested = [[1, 2], [3, [4, 5]]];
console.log(nested.flat());
console.log(nested.flat(Infinity));

Output

[ 1, 2, 3, [ 4, 5 ] ]
[ 1, 2, 3, 4, 5 ]

Explanation: flat(depth) removes nesting. Infinity flattens every level.

17. Chain map, filter and reduceIntermediate

Calculate the total price of in-stock items only.

Show solution
const items = [
  { name: 'Pen', price: 20, inStock: true },
  { name: 'Book', price: 350, inStock: false },
  { name: 'Bag', price: 899, inStock: true }
];
const total = items
  .filter(i => i.inStock)
  .map(i => i.price)
  .reduce((sum, p) => sum + p, 0);
console.log(total);

Output

919

Explanation: chaining small steps keeps each transformation simple and readable.

18. splice to insert and removeIntermediate

Insert 'verify email' at position 2 and remove 'logout'.

Show solution
const steps = ['register', 'login', 'logout', 'delete account'];
steps.splice(2, 0, 'verify email');
console.log(steps);
steps.splice(steps.indexOf('logout'), 1);
console.log(steps);

Output

[ 'register', 'login', 'verify email', 'logout', 'delete account' ]
[ 'register', 'login', 'verify email', 'delete account' ]

Explanation: splice(start, deleteCount, ...items) changes the array in place. It can remove and insert in one call.

19. Array destructuringIntermediate

Unpack the first item, the second item and the rest from a results array.

Show solution
const scores = [98, 87, 75, 60, 42];
const [top, second, ...others] = scores;
console.log(top, second);
console.log(others);

Output

98 87
[ 75, 60, 42 ]

Explanation: destructuring assigns array items to variables by position, and ...rest collects the remainder.

20. Group items by a keyIntermediate

Group tests by their status.

Show solution
const tests = [
  { id: 1, status: 'passed' }, { id: 2, status: 'failed' },
  { id: 3, status: 'passed' }, { id: 4, status: 'skipped' }
];
const groups = tests.reduce((acc, t) => {
  (acc[t.status] ||= []).push(t.id);
  return acc;
}, {});
console.log(groups);

Output

{ passed: [ 1, 3 ], failed: [ 2 ], skipped: [ 4 ] }

Explanation: reduce builds an object whose keys are statuses and whose values are arrays of IDs.

JavaScript Real-World QA Scenario Programs

21. Verify a list is sortedReal-world

Check whether prices read from the UI are sorted from low to high.

Show solution
const uiPrices = [199, 599, 599, 1499];
const isSorted = uiPrices.every((p, i) => i === 0 || uiPrices[i - 1] <= p);
console.log('Sorted ascending:', isSorted);
const expected = [...uiPrices].sort((a, b) => a - b);
console.log(JSON.stringify(uiPrices) === JSON.stringify(expected));

Output

Sorted ascending: true
true

Explanation: two common checks are comparing neighbours with every, or comparing with a sorted copy.

22. Compare expected and actual menu itemsReal-world

Find items that are missing from the UI and unexpected extras.

Show solution
const expected = ['Home', 'Shop', 'Blog', 'Contact'];
const actual = ['Home', 'Shop', 'Offers', 'Contact'];
const missing = expected.filter(x => !actual.includes(x));
const extra = actual.filter(x => !expected.includes(x));
console.log('Missing:', missing);
console.log('Extra:', extra);

Output

Missing: [ 'Blog' ]
Extra: [ 'Offers' ]

Explanation: two filters give a clear diff, which is easier to debug than a single equality check.

23. Count failed tests per browserReal-world

Count failures for each browser from a list of results.

Show solution
const results = [
  { browser: 'chromium', status: 'failed' },
  { browser: 'firefox', status: 'passed' },
  { browser: 'webkit', status: 'failed' },
  { browser: 'chromium', status: 'failed' }
];
const failures = {};
for (const r of results.filter(r => r.status === 'failed')) {
  failures[r.browser] = (failures[r.browser] || 0) + 1;
}
console.log(failures);

Output

{ chromium: 2, webkit: 1 }

Explanation: filter first, then count, keeping each step simple.

24. Top 3 slowest testsReal-world

Find the three slowest tests by duration.

Show solution
const durations = [
  { name: 'login', ms: 1200 }, { name: 'search', ms: 4300 },
  { name: 'checkout', ms: 8700 }, { name: 'profile', ms: 900 }, { name: 'cart', ms: 5100 }
];
const slowest = [...durations].sort((a, b) => b.ms - a.ms).slice(0, 3);
for (const t of slowest) console.log(`${t.name}: ${t.ms} ms`);

Output

checkout: 8700 ms
cart: 5100 ms
search: 4300 ms

Explanation: sort a copy in descending order, then slice the first three.

25. Paginate an arrayReal-world

Split 7 items into pages of 3 and print page 3.

Show solution
const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const pageSize = 3;
const page = n => items.slice((n - 1) * pageSize, n * pageSize);
console.log(page(1));
console.log(page(3));
console.log('Pages:', Math.ceil(items.length / pageSize));

Output

[ 'a', 'b', 'c' ]
[ 'g' ]
Pages: 3

Explanation: slice with start and end indexes calculated from the page number gives each page.

26. Chunk test cases for parallel workersReal-world

Split 10 test IDs into chunks for 3 workers.

Show solution
const tests = Array.from({ length: 10 }, (_, i) => `TC${i + 1}`);
const workers = 3;
const chunks = Array.from({ length: workers }, () => []);
tests.forEach((t, i) => chunks[i % workers].push(t));
chunks.forEach((c, i) => console.log(`Worker ${i + 1}: ${c.join(', ')}`));

Output

Worker 1: TC1, TC4, TC7, TC10
Worker 2: TC2, TC5, TC8
Worker 3: TC3, TC6, TC9

Explanation: distributing with i % workers balances the work, similar to how test runners spread tests.

27. Build a lookup from an arrayReal-world

Turn an array of users into an object keyed by ID.

Show solution
const users = [{ id: 7, name: 'Asha' }, { id: 9, name: 'Ravi' }];
const byId = Object.fromEntries(users.map(u => [u.id, u.name]));
console.log(byId);
console.log(byId[9]);

Output

{ '7': 'Asha', '9': 'Ravi' }
Ravi

Explanation: a lookup object gives fast access by key instead of searching the array each time.

28. Table data: average of a columnReal-world

Calculate the average price from table rows read as text.

Show solution
const rows = [
  ['Mouse', '₹599'],
  ['Keyboard', '₹1,499'],
  ['Cable', '₹199']
];
const prices = rows.map(([, price]) => Number(price.replace(/[^\d.]/g, '')));
const avg = prices.reduce((a, b) => a + b, 0) / prices.length;
console.log(prices);
console.log('Average:', avg.toFixed(2));

Output

[ 599, 1499, 199 ]
Average: 765.67

Explanation: map each row to a clean number, then reduce to the average. The leading comma in [, price] skips the first column.

29. Merge two result lists without duplicatesReal-world

Combine test IDs from two runs and keep each ID once, sorted.

Show solution
const run1 = ['TC3', 'TC1', 'TC5'];
const run2 = ['TC2', 'TC5', 'TC1'];
const all = [...new Set([...run1, ...run2])].sort();
console.log(all);

Output

[ 'TC1', 'TC2', 'TC3', 'TC5' ]

Explanation: spread both arrays into a Set to remove duplicates, then sort the result.

30. Find newly failing testsReal-world

Compare yesterday’s and today’s failures to find new ones.

Show solution
const yesterday = ['TC2', 'TC8'];
const today = ['TC2', 'TC5', 'TC9'];
const newFailures = today.filter(t => !yesterday.includes(t));
const fixed = yesterday.filter(t => !today.includes(t));
console.log('New failures:', newFailures.join(', '));
console.log('Fixed:', fixed.join(', '));

Output

New failures: TC5, TC9
Fixed: TC8

Explanation: set differences highlight regressions and fixes between runs.

31. Check all form fields are filledReal-world

Report which required fields are empty.

Show solution
const form = [
  { field: 'name', value: 'Asha' },
  { field: 'email', value: '' },
  { field: 'phone', value: '9876543210' },
  { field: 'city', value: '  ' }
];
const empty = form.filter(f => f.value.trim() === '').map(f => f.field);
console.log(empty.length ? `Empty: ${empty.join(', ')}` : 'All fields filled');

Output

Empty: email, city

Explanation: trimming first treats spaces-only values as empty, which matches most form validation rules.

32. Run async steps in orderReal-world

Run three async steps one after another and collect their results in order.

Show solution
const step = (name, ms) => new Promise(resolve => setTimeout(() => resolve(`${name} done`), ms));
const plan = [['login', 30], ['search', 10], ['logout', 20]];
const log = [];
for (const [name, ms] of plan) log.push(await step(name, ms));
console.log(log);

Output

[ 'login done', 'search done', 'logout done' ]

Explanation: for...of with await keeps the order, even though search is the fastest step. forEach would not wait.

33. Run independent requests in parallelReal-world

Run three independent async lookups in parallel with Promise.all and keep the input order.

Show solution
const fetchPrice = (sku, ms) => new Promise(resolve => setTimeout(() => resolve({ sku, price: ms * 10 }), ms));
const results = await Promise.all([fetchPrice('A1', 30), fetchPrice('B2', 10), fetchPrice('C3', 20)]);
console.log(results.map(r => `${r.sku}:${r.price}`).join(' '));

Output

A1:300 B2:100 C3:200

Explanation: Promise.all runs the work at the same time but returns results in the same order as the input array.

Keep Practising

Leave a Comment