Master JavaScript arrays with 20+ practical programs: sum, max, reverse, duplicates, sorting, searching, matrix operations, and real-world coding patterns.
The best way to master arrays is through hands-on programming. This guide provides 20+ carefully chosen problems — from beginner warmups to interview-level challenges — each with a clean solution, output, and explanation.
Program 2: Find Maximum and Minimum
const scores = [42, 17, 93, 5, 68, 31];
const max = Math.max(...scores);
const min = Math.min(...scores);
console.log("Max:", max);
console.log("Min:", min);
// Without spread (works for huge arrays too)
const max2 = scores.reduce((m, n) => n > m ? n : m, -Infinity);
console.log("Max (reduce):", max2);
Max: 93
Min: 5
Max (reduce): 93
Program 3: Reverse an Array
const arr = [1, 2, 3, 4, 5];
// Method 1: built-in reverse (mutates!)
const rev1 = [...arr].reverse();
console.log("Reversed:", rev1);
console.log("Original:", arr); // unchanged because we spread first
// Method 2: toReversed() — ES2023, no mutation
const rev2 = arr.toReversed();
console.log("toReversed:", rev2);
// Method 3: manual loop
function reverseArray(a) {
const result = [];
for (let i = a.length - 1; i >= 0; i--) result.push(a[i]);
return result;
}
console.log("Manual:", reverseArray(arr));
Reversed: [5, 4, 3, 2, 1]
Original: [1, 2, 3, 4, 5]
toReversed: [5, 4, 3, 2, 1]
Manual: [5, 4, 3, 2, 1]
Program 4: Remove Duplicates
const nums = [1, 2, 2, 3, 4, 4, 5, 1];
// Method 1: Set (cleanest)
const unique1 = [...new Set(nums)];
console.log("Set method:", unique1);
// Method 2: filter + indexOf
const unique2 = nums.filter((n, i) => nums.indexOf(n) === i);
console.log("Filter method:", unique2);
// Method 3: reduce
const unique3 = nums.reduce((acc, n) => {
if (!acc.includes(n)) acc.push(n);
return acc;
}, []);
console.log("Reduce method:", unique3);
Set method: [1, 2, 3, 4, 5]
Filter method: [1, 2, 3, 4, 5]
Reduce method: [1, 2, 3, 4, 5]
Program 5: Find Second Largest Element
function secondLargest(arr) {
const unique = [...new Set(arr)].sort((a, b) => b - a);
return unique.length >= 2 ? unique[1] : null;
}
console.log(secondLargest([12, 35, 1, 10, 34, 1])); // 34
console.log(secondLargest([10, 10, 10])); // null
console.log(secondLargest([3, 1])); // 1
Program 6: Count Occurrences of Each Element
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count);
// Find most frequent
const mostFrequent = Object.entries(count)
.sort(([, a], [, b]) => b - a)[0][0];
console.log("Most frequent:", mostFrequent);
{ apple: 3, banana: 2, cherry: 1 }
Most frequent: apple
Program 7: Flatten a Nested Array
const nested = [1, [2, 3], [4, [5, 6]], [7, [8, [9]]]];
// flat() with depth
console.log(nested.flat(1)); // [1, 2, 3, 4, [5,6], 7, [8,[9]]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6, 7, 8, [9]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Manual recursive flatten
function flattenDeep(arr) {
return arr.reduce((acc, item) =>
Array.isArray(item) ? [...acc, ...flattenDeep(item)] : [...acc, item],
[]);
}
console.log("Manual:", flattenDeep(nested));
[1, 2, 3, 4, [5, 6], 7, [8, [9]]]
[1, 2, 3, 4, 5, 6, 7, 8, [9]]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Manual: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Program 8: Rotate an Array
function rotateLeft(arr, k) {
const n = arr.length;
const shift = k % n;
return [...arr.slice(shift), ...arr.slice(0, shift)];
}
function rotateRight(arr, k) {
const n = arr.length;
const shift = k % n;
return [...arr.slice(n - shift), ...arr.slice(0, n - shift)];
}
const arr = [1, 2, 3, 4, 5];
console.log("Left by 2:", rotateLeft(arr, 2)); // [3, 4, 5, 1, 2]
console.log("Right by 2:", rotateRight(arr, 2)); // [4, 5, 1, 2, 3]
Left by 2: [3, 4, 5, 1, 2]
Right by 2: [4, 5, 1, 2, 3]
Program 9: Array Intersection and Union
const a = [1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7];
// Intersection (common elements)
const intersection = a.filter(n => b.includes(n));
console.log("Intersection:", intersection);
// Union (all unique elements)
const union = [...new Set([...a, ...b])];
console.log("Union:", union);
// Difference (in a but not in b)
const difference = a.filter(n => !b.includes(n));
console.log("Difference (a - b):", difference);
Intersection: [3, 4, 5]
Union: [1, 2, 3, 4, 5, 6, 7]
Difference (a - b): [1, 2]
Program 10: Two Sum Problem
Find two indices whose values sum to a target:
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement), i];
}
seen.set(nums[i], i);
}
return null;
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
console.log(twoSum([3, 2, 4], 6)); // [1, 2]
console.log(twoSum([1, 5, 3, 8], 11)); // [1, 3]
Program 11: Sort Array of Objects
const students = [
{ name: "Priya", grade: 88 },
{ name: "Arjun", grade: 95 },
{ name: "Meera", grade: 73 },
{ name: "Rohit", grade: 88 }
];
// Sort by grade descending, then name ascending
const sorted = [...students].sort((a, b) => {
if (b.grade !== a.grade) return b.grade - a.grade;
return a.name.localeCompare(b.name);
});
sorted.forEach(s => console.log(`${s.name}: ${s.grade}`));
Arjun: 95
Priya: 88
Rohit: 88
Meera: 73
Program 12: Chunk an Array
Split an array into groups of size n:
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
console.log(chunk(["a", "b", "c", "d", "e"], 2));
[[1, 2, 3], [4, 5, 6], [7]]
[["a", "b"], ["c", "d"], ["e"]]
Program 13: Group By Property
const orders = [
{ id: 1, status: "pending", amount: 200 },
{ id: 2, status: "shipped", amount: 450 },
{ id: 3, status: "pending", amount: 150 },
{ id: 4, status: "delivered", amount: 300 },
{ id: 5, status: "shipped", amount: 220 }
];
const grouped = orders.reduce((acc, order) => {
const key = order.status;
(acc[key] = acc[key] || []).push(order);
return acc;
}, {});
console.log("Pending count:", grouped.pending.length);
console.log("Shipped total:", grouped.shipped.reduce((s, o) => s + o.amount, 0));
Pending count: 2
Shipped total: 670
Program 14: Matrix Transpose
function transpose(matrix) {
return matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]));
}
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const transposed = transpose(matrix);
transposed.forEach(row => console.log(row));
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Program 15: Moving Average
function movingAverage(arr, window) {
return arr.map((_, i) => {
if (i < window - 1) return null;
const slice = arr.slice(i - window + 1, i + 1);
return slice.reduce((sum, n) => sum + n, 0) / window;
}).filter(v => v !== null);
}
const data = [2, 4, 6, 8, 10, 12];
console.log(movingAverage(data, 3));
Program 16: Zip Two Arrays
function zip(a, b) {
return a.map((item, i) => [item, b[i]]);
}
const names = ["Alice", "Bob", "Charlie"];
const scores = [92, 85, 78];
const zipped = zip(names, scores);
zipped.forEach(([name, score]) => console.log(`${name}: ${score}`));
Alice: 92
Bob: 85
Charlie: 78
Program 17: Pipe / Compose Functions
// Pipe: applies functions left to right
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const process = pipe(
arr => arr.filter(n => n % 2 === 0), // keep evens
arr => arr.map(n => n * 3), // triple
arr => arr.reduce((sum, n) => sum + n, 0) // sum
);
console.log(process([1, 2, 3, 4, 5, 6])); // 2+4+6 → 6+12+18 = 36
Program 18: Frequency Map → Sorted
const words = ["the", "fox", "the", "quick", "fox", "the", "brown"];
const freq = words.reduce((acc, w) => ({ ...acc, [w]: (acc[w] || 0) + 1 }), {});
const sorted = Object.entries(freq)
.sort(([, a], [, b]) => b - a)
.map(([word, count]) => `${word}: ${count}`);
console.log(sorted);
["the: 3", "fox: 2", "quick: 1", "brown: 1"]
Program 19: Paginate an Array
function paginate(arr, page, pageSize) {
const start = (page - 1) * pageSize;
return {
data: arr.slice(start, start + pageSize),
page,
pageSize,
total: arr.length,
totalPages: Math.ceil(arr.length / pageSize)
};
}
const items = Array.from({ length: 25 }, (_, i) => `Item ${i + 1}`);
const page2 = paginate(items, 2, 5);
console.log(page2.data);
console.log(`Page ${page2.page} of ${page2.totalPages}`);
["Item 6", "Item 7", "Item 8", "Item 9", "Item 10"]
Page 2 of 5
Program 20: Deep Clone an Array of Objects
const original = [
{ id: 1, tags: ["js", "node"] },
{ id: 2, tags: ["react", "ts"] }
];
// Shallow copy — WRONG for nested objects
const shallowCopy = [...original];
shallowCopy[0].tags.push("vue");
console.log("Original tags:", original[0].tags); // ["js", "node", "vue"] — mutated!
// Deep clone — using structuredClone (modern)
const original2 = [
{ id: 1, tags: ["js", "node"] },
{ id: 2, tags: ["react", "ts"] }
];
const deepCopy = structuredClone(original2);
deepCopy[0].tags.push("vue");
console.log("Original2 tags:", original2[0].tags); // ["js", "node"] — safe!
console.log("Deep copy tags:", deepCopy[0].tags); // ["js", "node", "vue"]
Original tags: ["js", "node", "vue"]
Original2 tags: ["js", "node"]
Deep copy tags: ["js", "node", "vue"]
Cheat Sheet: Common Array Programs
| Task | One-liner |
|---|
| Sum | arr.reduce((a, b) => a + b, 0) |
| Max | Math.max(...arr) |
| Min | Math.min(...arr) |
| Unique | [...new Set(arr)] |
| Reverse | [...arr].reverse() |
| Flatten | arr.flat(Infinity) |
| Frequency | `arr.reduce((a, v) => ({...a, [v]: (a[v] | | 0)+1}), {})` |
| Group by | `arr.reduce((a, v) => ({ ...a, [v.key]: [...(a[v.key] | | []), v] }), {})` |
| Chunk | Array.from({length: Math.ceil(arr.length/n)}, (_, i) => arr.slice(i*n, i*n+n)) |
| Zip | a.map((item, i) => [item, b[i]]) |
Interview Questions
Q1. Write a program to find all pairs in an array that sum to a given target.
Use a Set to track seen values. For each element, check if target - element is in the set.
Q2. How do you remove all falsy values from an array?
const clean = [0, 1, false, 2, "", 3, null].filter(Boolean);
// [1, 2, 3]
Q3. How would you find the most frequent element?
Use reduce() to build a frequency map, then Object.entries() to find the max.
Q4. What is the difference between flat() and flatMap()?
flat(depth) flattens nested arrays to a given depth. flatMap(fn) is equivalent to .map(fn).flat(1) — it maps and then flattens one level in a single pass.
Q5. How do you merge two sorted arrays into one sorted array?
function mergeSorted(a, b) {
return [...a, ...b].sort((x, y) => x - y);
}
console.log(mergeSorted([1, 3, 5], [2, 4, 6])); // [1, 2, 3, 4, 5, 6]
Q6. How do you find duplicate values in an array?
const arr = [1, 2, 2, 3, 3, 3];
const dups = arr.filter((v, i) => arr.indexOf(v) !== i);
console.log([...new Set(dups)]); // [2, 3]
Q7. How do you convert an array of key-value pairs to an object?
const pairs = [["name", "Alice"], ["age", 30]];
const obj = Object.fromEntries(pairs);
// { name: "Alice", age: 30 }
Key Takeaways
reduce() is the Swiss Army knife — it can implement sum, max, count, group, flatten, and more- Always spread before mutating methods if you want to preserve the original:
[...arr].reverse() Set is the fastest way to deduplicate an arraystructuredClone() is the modern, safe way to deep-clone arrays of objects- Build a habit of writing the expected output in comments — it catches bugs early