Practice Questions — Arrays and Array Methods
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output of the following code?
const arr = [10, 20, 30];
console.log(arr[1]);Arrays are zero-indexed. Index 1 is the second element.
20Question 2
Easy
What is the output?
const arr = [1, 2, 3];
arr.push(4);
console.log(arr);push adds an element to the end.
[1, 2, 3, 4]Question 3
Easy
What is the output?
const arr = ["a", "b", "c"];
console.log(arr.length);
console.log(arr[arr.length - 1]);length is 3. The last index is length - 1.
3cQuestion 4
Easy
What is the output?
const nums = [5, 10, 15];
const doubled = nums.map(n => n * 2);
console.log(doubled);map transforms each element and returns a new array.
[10, 20, 30]Question 5
Easy
What is the output?
const nums = [1, 2, 3, 4, 5];
const even = nums.filter(n => n % 2 === 0);
console.log(even);filter keeps elements where the callback returns true.
[2, 4]Question 6
Easy
What is the output?
const arr = [10, 20, 30];
console.log(arr.includes(20));
console.log(arr.includes(25));includes returns true if the value is in the array.
truefalseQuestion 7
Medium
What is the output?
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum);reduce accumulates: 0+1=1, 1+2=3, 3+3=6, 6+4=10, 10+5=15.
15Question 8
Medium
What is the output?
const arr = [3, 1, 4, 1, 5];
const sorted = [...arr].sort((a, b) => a - b);
console.log(sorted);
console.log(arr);Spreading creates a copy. Sort modifies the copy, not the original.
[1, 1, 3, 4, 5][3, 1, 4, 1, 5]Question 9
Medium
What is the output?
const arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 4));
console.log(arr.slice(3));slice(start, end) extracts from start up to (not including) end.
[2, 3, 4][4, 5]Question 10
Medium
What is the output?
const students = [
{ name: "Aarav", score: 72 },
{ name: "Priya", score: 91 },
{ name: "Rohan", score: 85 }
];
const top = students.find(s => s.score > 80);
console.log(top.name);find returns the FIRST element that matches.
PriyaQuestion 11
Medium
What is the output?
const [a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a);
console.log(b);
console.log(rest);Destructuring with rest pattern collects remaining elements.
1020[30, 40, 50]Question 12
Hard
What is the output?
const nums = [1, 2, 3, 4, 5, 6];
const result = nums
.filter(n => n % 2 === 0)
.map(n => n * n);
console.log(result);Filter even numbers first, then square each one.
[4, 16, 36]Question 13
Hard
What is the output?
const words = ["hello", "world", "javascript"];
const result = words.reduce((longest, word) => {
return word.length > longest.length ? word : longest;
}, "");
console.log(result);reduce finds the longest word by comparing lengths.
javascriptQuestion 14
Hard
What is the output?
const nums = [1, 2, 3, 4, 5];
const result = nums.reduce((acc, n) => {
acc[n % 2 === 0 ? "even" : "odd"].push(n);
return acc;
}, { even: [], odd: [] });
console.log(result);reduce builds an object that groups numbers into even and odd arrays.
{ even: [2, 4], odd: [1, 3, 5] }Question 15
Hard
What is the output?
const a = [1, 2, 3];
const b = [3, 4, 5];
const unique = [...new Set([...a, ...b])];
console.log(unique);Spread both arrays, use a Set to remove duplicates, spread back to array.
[1, 2, 3, 4, 5]Question 16
Medium
What is the difference between map and forEach? When would you use each one?
One returns a new array, the other returns undefined.
map transforms each element and returns a new array with the results. forEach runs a function for each element but returns undefined. Use map when you need to transform data into a new array. Use forEach for side effects like logging, updating DOM elements, or other operations where you do not need a return value.Question 17
Medium
What is the output?
const ages = [12, 18, 15, 21, 16];
console.log(ages.every(a => a >= 18));
console.log(ages.some(a => a >= 18));every checks ALL elements. some checks if ANY element passes.
falsetrueQuestion 18
Easy
What is the output?
const arr = ["a", "b", "c"];
const removed = arr.pop();
console.log(removed);
console.log(arr);pop removes and returns the last element.
c["a", "b"]Question 19
Hard
What is the output?
const data = [[1, 2], [3, 4], [5, 6]];
const flat = data.flat();
const sum = flat.reduce((a, b) => a + b, 0);
console.log(flat);
console.log(sum);flat flattens one level of nesting. Then reduce sums them all.
[1, 2, 3, 4, 5, 6]21Question 20
Medium
What is the output?
const arr = [1, 2, 3, 4, 5];
const idx = arr.findIndex(n => n > 3);
console.log(idx);findIndex returns the INDEX of the first matching element.
3Mixed & Application Questions
Question 1
Easy
What is the output?
const arr = ["x", "y", "z"];
arr.unshift("w");
console.log(arr);unshift adds to the start of the array.
["w", "x", "y", "z"]Question 2
Easy
What is the output?
const names = ["Aarav", "Priya", "Rohan"];
console.log(names.indexOf("Priya"));
console.log(names.indexOf("Diya"));indexOf returns the index or -1 if not found.
1-1Question 3
Medium
What is the output?
const nums = [10, 20, 30, 40, 50];
const result = nums
.filter(n => n >= 20)
.map(n => n / 10);
console.log(result);Filter first (>= 20), then divide each by 10.
[2, 3, 4, 5]Question 4
Medium
What is the output?
const a = [1, 2];
const b = [3, 4];
const c = [...a, ...b, 5];
console.log(c);Spread unpacks arrays. You can add extra elements too.
[1, 2, 3, 4, 5]Question 5
Medium
What is the output?
const arr = ["hello", "world", "test"];
const result = arr.map(s => s.toUpperCase());
console.log(result);map transforms each string to uppercase.
["HELLO", "WORLD", "TEST"]Question 6
Medium
What is the output?
const scores = [85, 42, 91, 67, 38];
const passCount = scores.filter(s => s >= 50).length;
console.log(passCount);Filter, then check the length of the filtered array.
3Question 7
Hard
What is the output?
const students = [
{ name: "Aarav", marks: 85 },
{ name: "Priya", marks: 92 },
{ name: "Rohan", marks: 78 },
{ name: "Diya", marks: 95 }
];
const toppers = students
.filter(s => s.marks >= 85)
.sort((a, b) => b.marks - a.marks)
.map(s => s.name);
console.log(toppers);Filter >= 85, sort descending by marks, extract names.
["Diya", "Priya", "Aarav"]Question 8
Hard
What is the output?
const words = ["cat", "elephant", "dog", "hippopotamus"];
const longest = words.reduce((a, b) => a.length >= b.length ? a : b);
console.log(longest);reduce compares each word's length to find the longest.
hippopotamusQuestion 9
Hard
What is the output?
const arr = Array.from({ length: 5 }, (_, i) => i * i);
console.log(arr);Array.from with a mapping function. The second parameter (i) is the index.
[0, 1, 4, 9, 16]Question 10
Hard
What is the output?
const data = [
{ category: "fruit", name: "apple" },
{ category: "veg", name: "carrot" },
{ category: "fruit", name: "mango" },
{ category: "veg", name: "potato" }
];
const grouped = data.reduce((acc, item) => {
if (!acc[item.category]) acc[item.category] = [];
acc[item.category].push(item.name);
return acc;
}, {});
console.log(grouped);reduce groups items by category into an object.
{ fruit: ["apple", "mango"], veg: ["carrot", "potato"] }Question 11
Hard
Explain the difference between slice and splice. Which one modifies the original array?
One copies, the other cuts.
slice(start, end) creates a new array from a portion of the original without modifying it. splice(start, deleteCount, ...items) modifies the original array by removing, replacing, or inserting elements at a specified position. splice modifies the original, slice does not.Question 12
Easy
What is the output?
const arr = [1, 2, 3, 4];
const shifted = arr.shift();
console.log(shifted);
console.log(arr);shift removes and returns the first element.
1[2, 3, 4]Question 13
Medium
What is the output?
const sentences = ["hello world", "foo bar baz"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words);flatMap maps then flattens one level.
["hello", "world", "foo", "bar", "baz"]Multiple Choice Questions
MCQ 1
What index does the first element of an array have?
Answer: B
B is correct. Arrays in JavaScript are zero-indexed. The first element is always at index 0, the second at index 1, and so on.
B is correct. Arrays in JavaScript are zero-indexed. The first element is always at index 0, the second at index 1, and so on.
MCQ 2
Which method adds an element to the END of an array?
Answer: C
C is correct.
C is correct.
push() adds to the end. unshift() adds to the start. pop() removes from the end. shift() removes from the start.MCQ 3
Which method returns a new array with transformed elements?
Answer: B
B is correct.
B is correct.
map() calls a function on each element and returns a new array with the results. forEach returns undefined. filter returns selected elements. reduce returns a single value.MCQ 4
What does [1, 2, 3].includes(2) return?
Answer: B
B is correct.
B is correct.
includes() returns a boolean: true if the value is found in the array, false if not. Since 2 is in the array, it returns true.MCQ 5
What does arr.pop() return?
Answer: B
B is correct.
B is correct.
pop() removes the last element from the array and returns that removed element. push() is the one that returns the new length.MCQ 6
What is the default sorting behavior of arr.sort()?
Answer: C
C is correct. By default,
C is correct. By default,
sort() converts elements to strings and sorts them by Unicode code points (alphabetically). This is why [40, 100, 1] sorts as [1, 100, 40] - because "100" comes before "40" as strings.MCQ 7
What does filter() return if no elements match the condition?
Answer: C
C is correct.
C is correct.
filter() always returns an array. If no elements pass the test, it returns an empty array []. It never returns null, undefined, or false.MCQ 8
Which method modifies the original array?
Answer: D
D is correct.
D is correct.
sort() modifies the original array in place. map(), filter(), and slice() all return new arrays without changing the original.MCQ 9
What does the spread operator [...arr] do?
Answer: B
B is correct.
B is correct.
[...arr] creates a shallow copy of the array. It does not reverse (option A), flatten deeply nested arrays (option C), or remove duplicates (option D - use a Set for that).MCQ 10
What is the second argument to reduce()?
Answer: C
C is correct.
C is correct.
reduce(callback, initialValue) takes a callback as the first argument and an optional initial value for the accumulator as the second. Always provide an initial value to avoid errors with empty arrays.MCQ 11
What is the result of [1, 2, 3].map(n => n > 1)?
Answer: B
B is correct.
B is correct.
map transforms each element using the callback. 1 > 1 is false, 2 > 1 is true, 3 > 1 is true. The result is [false, true, true]. If you wanted [2, 3], you would use filter instead.MCQ 12
What does Array.from({length: 3}, (_, i) => i) return?
Answer: B
B is correct.
B is correct.
Array.from creates an array of length 3 and calls the mapping function for each index. The function receives the element (undefined, which we ignore with _) and the index. It returns [0, 1, 2].MCQ 13
What is the difference between find() and filter()?
Answer: B
B is correct.
B is correct.
find returns the first element that matches (or undefined if none match). filter returns a new array with ALL elements that match (or an empty array if none match). find stops at the first match; filter checks every element.MCQ 14
What does [1, [2, [3]]].flat() return?
Answer: B
B is correct. By default,
B is correct. By default,
flat() flattens one level of nesting. The outer array [1, [2, [3]]] becomes [1, 2, [3]]. The inner [3] is not flattened because it is at depth 2. Use flat(2) or flat(Infinity) to flatten deeper.MCQ 15
What does arr.length return?
Answer: B
B is correct.
B is correct.
length returns the total number of elements in the array. The last index is length - 1 (option A). JavaScript arrays do not have a fixed capacity (option D).MCQ 16
How do you correctly sort numbers in ascending order?
Answer: C
C is correct.
C is correct.
(a, b) => a - b sorts numbers ascending. If a < b, the result is negative (a comes first). If a > b, the result is positive (b comes first). Option B sorts descending.Coding Challenges
Challenge 1: Find the Maximum Value
EasyAarav has the array [23, 67, 12, 89, 45, 91, 34]. Write a program using reduce to find the maximum value without using Math.max.
Sample Input
(No input required)
Sample Output
Maximum: 91
Use reduce. Do not use Math.max or sort.
const nums = [23, 67, 12, 89, 45, 91, 34];
const max = nums.reduce((a, b) => a > b ? a : b);
console.log("Maximum:", max);Challenge 2: Remove Duplicates
EasyPriya has the array [1, 3, 5, 3, 7, 1, 9, 5]. Write a program to remove duplicates and return a sorted array.
Sample Input
(No input required)
Sample Output
[1, 3, 5, 7, 9]
Use the Set object and spread operator.
const arr = [1, 3, 5, 3, 7, 1, 9, 5];
const unique = [...new Set(arr)].sort((a, b) => a - b);
console.log(unique);Challenge 3: Student Grade Report
MediumGiven an array of student objects [{name: "Aarav", marks: 85}, {name: "Priya", marks: 42}, {name: "Rohan", marks: 91}, {name: "Diya", marks: 67}, {name: "Vikram", marks: 38}], use method chaining to: (1) filter students who passed (marks >= 50), (2) sort by marks descending, (3) map to strings like "Rohan: 91".
Sample Input
(No input required)
Sample Output
Rohan: 91
Aarav: 85
Diya: 67
Use filter, sort, and map chained together.
const students = [
{ name: "Aarav", marks: 85 },
{ name: "Priya", marks: 42 },
{ name: "Rohan", marks: 91 },
{ name: "Diya", marks: 67 },
{ name: "Vikram", marks: 38 }
];
students
.filter(s => s.marks >= 50)
.sort((a, b) => b.marks - a.marks)
.map(s => s.name + ": " + s.marks)
.forEach(line => console.log(line));Challenge 4: Group By Category
MediumKavya has an array of products: [{name: "Apple", type: "fruit"}, {name: "Carrot", type: "vegetable"}, {name: "Mango", type: "fruit"}, {name: "Potato", type: "vegetable"}, {name: "Banana", type: "fruit"}]. Use reduce to group them by type.
Sample Input
(No input required)
Sample Output
{ fruit: ["Apple", "Mango", "Banana"], vegetable: ["Carrot", "Potato"] }
Use reduce with an object as the accumulator.
const products = [
{ name: "Apple", type: "fruit" },
{ name: "Carrot", type: "vegetable" },
{ name: "Mango", type: "fruit" },
{ name: "Potato", type: "vegetable" },
{ name: "Banana", type: "fruit" }
];
const grouped = products.reduce((acc, p) => {
if (!acc[p.type]) acc[p.type] = [];
acc[p.type].push(p.name);
return acc;
}, {});
console.log(grouped);Challenge 5: Flatten and Sum Nested Arrays
MediumArjun has the nested array [[10, 20], [30, 40], [50]]. Write a program that flattens it and calculates the sum using flat and reduce.
Sample Input
(No input required)
Sample Output
Flat: [10, 20, 30, 40, 50]
Sum: 150
Use flat() and reduce().
const nested = [[10, 20], [30, 40], [50]];
const flat = nested.flat();
const sum = flat.reduce((acc, n) => acc + n, 0);
console.log("Flat:", flat);
console.log("Sum:", sum);Challenge 6: Word Frequency Counter
HardMeera has the string "the cat sat on the mat the cat". Write a program that splits the string into words and uses reduce to count the frequency of each word.
Sample Input
(No input required)
Sample Output
{ the: 3, cat: 2, sat: 1, on: 1, mat: 1 }
Use split and reduce.
const text = "the cat sat on the mat the cat";
const freq = text.split(" ").reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {});
console.log(freq);Challenge 7: Intersection of Two Arrays
HardRohan has two arrays: [1, 2, 3, 4, 5] and [3, 4, 5, 6, 7]. Write a program to find the common elements (intersection) and the elements unique to each array (difference).
Sample Input
(No input required)
Sample Output
Common: [3, 4, 5]
Only in A: [1, 2]
Only in B: [6, 7]
Use filter and includes.
const a = [1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7];
const common = a.filter(x => b.includes(x));
const onlyA = a.filter(x => !b.includes(x));
const onlyB = b.filter(x => !a.includes(x));
console.log("Common:", common);
console.log("Only in A:", onlyA);
console.log("Only in B:", onlyB);Challenge 8: Build Product Cards from Data
HardDiya has an array of products: [{name: "Laptop", price: 45000}, {name: "Phone", price: 15000}, {name: "Watch", price: 8000}]. Use map to generate HTML card strings for each product using template literals, then join them together.
Sample Input
(No input required)
Sample Output
(Three HTML card divs with product name and price)
Use map and template literals. Generate valid HTML strings.
const products = [
{ name: "Laptop", price: 45000 },
{ name: "Phone", price: 15000 },
{ name: "Watch", price: 8000 }
];
const cards = products.map(p => {
return `<div class="card">
<h3>${p.name}</h3>
<p>Rs ${p.price.toLocaleString()}</p>
</div>`;
});
console.log(cards.join("\n"));Challenge 9: Custom Array Method: chunk
HardWrite a function chunk(arr, size) that splits an array into groups of the given size. For example, chunk([1,2,3,4,5], 2) should return [[1,2], [3,4], [5]].
Sample Input
chunk([1, 2, 3, 4, 5, 6, 7], 3)
Sample Output
[[1, 2, 3], [4, 5, 6], [7]]
Use a loop with slice. Return a new array of arrays.
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([1, 2, 3, 4, 5], 2));Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn web development with a live mentor?
Explore our Frontend Masterclass