Chapter 23 Advanced 50 Questions

Practice Questions — Advanced Array and Object Patterns

← Back to Notes
8 Easy
10 Medium
9 Hard

Topic-Specific Questions

Question 1
Easy
What is the output?
const nums = [1, 2, 3, 4, 5];
const result = nums.filter(function(n) { return n > 2; }).map(function(n) { return n * 10; });
console.log(result);
filter keeps numbers > 2, then map multiplies each by 10.
[30, 40, 50]
Question 2
Easy
What is the output?
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));
console.log(Object.values(obj));
Object.keys returns property names. Object.values returns property values.
["a", "b", "c"]
[1, 2, 3]
Question 3
Easy
What is the output?
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];
console.log(unique);
A Set only keeps unique values. Spread converts it back to an array.
[1, 2, 3]
Question 4
Easy
What is the output?
const nested = [[1, 2], [3, 4], [5, 6]];
console.log(nested.flat());
flat() flattens one level of nesting by default.
[1, 2, 3, 4, 5, 6]
Question 5
Medium
What is the output?
const student = {
  name: "Priya",
  scores: { maths: 95, science: 88 }
};
const { name, scores: { maths } } = student;
console.log(name);
console.log(maths);
Nested destructuring extracts values from nested objects.
Priya
95
Question 6
Medium
What is the output?
const key = "color";
const obj = { [key]: "purple", size: 10 };
console.log(obj);
console.log(obj.color);
Square brackets in object literals compute the property name from a variable.
{ color: "purple", size: 10 }
purple
Question 7
Medium
What is the output?
const entries = [["x", 1], ["y", 2], ["z", 3]];
const obj = Object.fromEntries(entries);
console.log(obj);
console.log(obj.y);
Object.fromEntries converts [key, value] pairs into an object.
{ x: 1, y: 2, z: 3 }
2
Question 8
Medium
What is the output?
const original = { a: 1, nested: { b: 2 } };
const copy = { ...original };
copy.a = 99;
copy.nested.b = 99;
console.log(original.a);
console.log(original.nested.b);
Spread creates a shallow copy. Top-level properties are independent, but nested objects are shared.
1
99
Question 9
Hard
What is the output?
const items = [
  { name: "A", cat: "X" },
  { name: "B", cat: "Y" },
  { name: "C", cat: "X" },
  { name: "D", cat: "Y" },
  { name: "E", cat: "X" }
];
const grouped = items.reduce(function(acc, item) {
  if (!acc[item.cat]) acc[item.cat] = [];
  acc[item.cat].push(item.name);
  return acc;
}, {});
console.log(grouped);
console.log(grouped.X.length);
reduce groups items by their cat property.
{ X: ["A", "C", "E"], Y: ["B", "D"] }
3
Question 10
Hard
What is the output?
const data = [1, [2, [3, [4]]]];
console.log(data.flat(1));
console.log(data.flat(2));
console.log(data.flat(Infinity));
flat(n) flattens n levels of nesting.
[1, 2, [3, [4]]]
[1, 2, 3, [4]]
[1, 2, 3, 4]
Question 11
Hard
What is the output?
const scores = { maths: 40, science: 50, english: 30 };
const doubled = Object.fromEntries(
  Object.entries(scores).map(function([key, val]) {
    return [key, val * 2];
  })
);
console.log(doubled);
entries -> map (double values) -> fromEntries creates a new object.
{ maths: 80, science: 100, english: 60 }
Question 12
Medium
What is the difference between a shallow copy and a deep copy?
Think about what happens to nested objects.
A shallow copy copies only the top-level properties. Nested objects and arrays inside the copy still point to the same references as the original. If you modify a nested property in the copy, the original is also affected. A deep copy recursively copies everything, creating completely independent nested objects.
Question 13
Hard
Why should you copy an array before sorting it? When is it OK not to?
Think about what sort() does to the original array.
sort() mutates the original array in place. If other parts of your code rely on the original order, sorting without copying will break them. You should copy first: [...array].sort(). It is OK to sort without copying if the array is temporary or you no longer need the original order (for example, you just loaded it from an API and want it sorted before displaying).
Question 14
Easy
What is the output?
const arr = [3, 1, 2];
const sorted = [...arr].sort();
console.log(arr);
console.log(sorted);
Spread creates a copy. Sort without a comparator sorts as strings.
[3, 1, 2]
[1, 2, 3]
Question 15
Easy
What is the output?
const obj = { name: 'Aarav', age: 15 };
const copy = { ...obj, age: 16 };
console.log(obj.age);
console.log(copy.age);
Spread copies all properties. Later properties override earlier ones.
15
16
Question 16
Medium
What is the output?
const data = [
  { name: 'A', score: 10 },
  { name: 'B', score: 30 },
  { name: 'C', score: 20 }
];
const max = data.reduce(function(best, item) {
  return item.score > best.score ? item : best;
});
console.log(max.name);
reduce without initial value starts with the first element as accumulator.
B
Question 17
Medium
What is the output?
const users = [
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 1, name: 'A' }
];
const unique = [...new Map(
  users.map(function(u) { return [u.id, u]; })
).values()];
console.log(unique.length);
Map keys are unique. Duplicate id=1 is overwritten.
2
Question 18
Hard
What is the output?
const items = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const freq = items.reduce(function(acc, item) {
  acc[item] = (acc[item] || 0) + 1;
  return acc;
}, {});
const sorted = Object.entries(freq).sort(function(a, b) { return b[1] - a[1]; });
console.log(sorted[0]);
reduce counts frequencies. entries + sort finds the most common.
["apple", 3]

Mixed & Application Questions

Question 1
Easy
What is the output?
const words = ["hello world", "good morning"];
const result = words.flatMap(function(w) { return w.split(" "); });
console.log(result);
flatMap maps each element and flattens the result by one level.
["hello", "world", "good", "morning"]
Question 2
Easy
What is the output?
const obj = { a: 1, b: 2, c: 3 };
const sum = Object.values(obj).reduce(function(s, v) { return s + v; }, 0);
console.log(sum);
Object.values gives [1, 2, 3]. reduce sums them.
6
Question 3
Medium
What is the output?
const students = [
  { name: "Aarav", score: 85 },
  { name: "Priya", score: 92 },
  { name: "Rohan", score: 78 }
];
const best = students.reduce(function(max, s) {
  return s.score > max.score ? s : max;
});
console.log(best.name);
reduce without initial value starts with the first element.
Priya
Question 4
Medium
What is the output?
const arr = [3, 1, 4, 1, 5, 9];
const sorted = [...arr].sort(function(a, b) { return a - b; });
console.log(arr);
console.log(sorted);
Spreading creates a copy. The original is not affected.
[3, 1, 4, 1, 5, 9]
[1, 1, 3, 4, 5, 9]
Question 5
Medium
What is the output?
const people = [
  { name: "Aarav" },
  { name: "Priya" },
  { name: "Aarav" }
];
const names = people.map(function(p) { return p.name; });
const unique = [...new Set(names)];
console.log(unique);
Map extracts names, Set removes duplicates.
["Aarav", "Priya"]
Question 6
Hard
What is the output?
const cart = [
  { item: "Pen", price: 10, qty: 5 },
  { item: "Book", price: 200, qty: 2 },
  { item: "Eraser", price: 5, qty: 10 }
];
const total = cart
  .map(function(i) { return i.price * i.qty; })
  .reduce(function(sum, val) { return sum + val; }, 0);
console.log(total);
map calculates each line total, reduce sums them.
500
Question 7
Hard
What is the output?
const data = [
  { name: "Aarav", grade: "A" },
  { name: "Priya", grade: "B" },
  { name: "Rohan", grade: "A" },
  { name: "Meera", grade: "A" },
  { name: "Kavya", grade: "B" }
];

const countByGrade = data.reduce(function(acc, s) {
  acc[s.grade] = (acc[s.grade] || 0) + 1;
  return acc;
}, {});
console.log(countByGrade);
This counts how many students have each grade.
{ A: 3, B: 2 }
Question 8
Hard
What is the output?
const obj = { a: 10, b: 20, c: 30 };
const filtered = Object.fromEntries(
  Object.entries(obj).filter(function([k, v]) { return v >= 20; })
);
console.log(filtered);
console.log(Object.keys(filtered).length);
entries -> filter (keep values >= 20) -> fromEntries.
{ b: 20, c: 30 }
2
Question 9
Hard
What is the output?
const original = { x: 1, arr: [2, 3] };
const deep = structuredClone(original);
deep.x = 99;
deep.arr.push(4);
console.log(original.x);
console.log(original.arr);
structuredClone creates a completely independent deep copy.
1
[2, 3]

Multiple Choice Questions

MCQ 1
Which method removes duplicate values from an array?
  • A. array.unique()
  • B. [...new Set(array)]
  • C. array.distinct()
  • D. array.filter(unique)
Answer: B
B is correct. new Set(array) creates a Set with unique values. Spreading it back into an array gives a deduplicated array.
MCQ 2
What does Object.entries({ a: 1, b: 2 }) return?
  • A. ["a", "b"]
  • B. [1, 2]
  • C. [["a", 1], ["b", 2]]
  • D. { a: 1, b: 2 }
Answer: C
C is correct. Object.entries returns an array of [key, value] pairs.
MCQ 3
What does array.flat() do?
  • A. Sorts the array
  • B. Removes duplicates
  • C. Flattens nested arrays by one level
  • D. Reverses the array
Answer: C
C is correct. flat() without arguments flattens one level of nesting. Pass a number for deeper flattening or Infinity for complete flattening.
MCQ 4
What is the correct way to create a deep copy of an object?
  • A. Object.assign({}, obj)
  • B. { ...obj }
  • C. structuredClone(obj)
  • D. obj.clone()
Answer: C
C is correct. structuredClone() creates a true deep copy. Object.assign and spread only create shallow copies.
MCQ 5
What does Object.fromEntries do?
  • A. Converts an object to an array
  • B. Converts an array of [key, value] pairs into an object
  • C. Returns the first entry of an object
  • D. Deletes entries from an object
Answer: B
B is correct. Object.fromEntries is the reverse of Object.entries. It takes [["a", 1], ["b", 2]] and returns { a: 1, b: 2 }.
MCQ 6
Why should you write [...array].sort() instead of array.sort()?
  • A. sort() does not work on arrays
  • B. sort() mutates the original array, spreading creates a safe copy first
  • C. Spreading makes sort() faster
  • D. sort() only works on copied arrays
Answer: B
B is correct. sort() modifies the array in place. If you need to keep the original order, spread into a new array first.
MCQ 7
What is the purpose of reduce when grouping data?
  • A. To remove items from the array
  • B. To accumulate items into an object where each key holds a group of items
  • C. To sort items into groups alphabetically
  • D. To count the total number of items
Answer: B
B is correct. reduce starts with an empty object and adds each item to the appropriate group (array) based on a property value.
MCQ 8
What is a computed property name in JavaScript?
  • A. A property calculated at compile time
  • B. A property name inside square brackets that is evaluated at runtime
  • C. A property that computes its value automatically
  • D. A read-only property
Answer: B
B is correct. { [expression]: value } evaluates the expression to determine the property name. Example: { ["na" + "me"]: "Aarav" } creates { name: "Aarav" }.
MCQ 9
What does flatMap do differently from map followed by flat?
  • A. flatMap is faster because it combines both steps
  • B. flatMap can flatten multiple levels, map+flat cannot
  • C. flatMap only flattens one level, just like map then flat(1)
  • D. There is no difference
Answer: C
C is correct. flatMap is equivalent to calling map then flat(1). It only flattens one level. It is slightly more efficient because it does both steps in one pass.
MCQ 10
Which method is best for converting an array to an object for O(1) lookups by ID?
  • A. array.find()
  • B. Object.fromEntries(array.map(item => [item.id, item]))
  • C. array.reduce() with a counter
  • D. array.indexOf()
Answer: B
B is correct. This creates an object keyed by ID, allowing instant O(1) lookups. find() and indexOf() search the array each time (O(n)).
MCQ 11
What happens when you use JSON.parse(JSON.stringify(obj)) as a deep clone?
  • A. It works perfectly for all objects
  • B. It works for plain data but loses functions, undefined, Date objects, and Map/Set
  • C. It is faster than structuredClone
  • D. It creates a shallow copy
Answer: B
B is correct. JSON.stringify cannot serialize functions, undefined, Infinity, NaN, Date objects (converts to strings), Map, Set, or circular references. structuredClone handles most of these better.
MCQ 12
How do you sort an array of objects by a string property alphabetically?
  • A. array.sort()
  • B. array.sort((a, b) => a.name - b.name)
  • C. array.sort((a, b) => a.name.localeCompare(b.name))
  • D. array.alphabetize("name")
Answer: C
C is correct. localeCompare compares strings properly for sorting, handling different languages and special characters.
MCQ 13
What does the spread operator do in [...array]?
  • A. Deletes the array
  • B. Creates a shallow copy of the array
  • C. Creates a deep copy of the array
  • D. Reverses the array
Answer: B
B is correct. The spread operator [...array] creates a shallow copy. Top-level elements are copied, but nested objects are still shared references.
MCQ 14
What does array.reduce() return when used with an initial value of {}?
  • A. Always an empty object
  • B. An object built by the callback function
  • C. The original array
  • D. An error
Answer: B
B is correct. reduce with {} as the initial value starts with an empty object. The callback builds up this object by adding/modifying properties in each iteration.
MCQ 15
What is the time complexity of looking up a value in a lookup map (Object/Map) vs using array.find()?
  • A. Both are O(1)
  • B. Both are O(n)
  • C. Object/Map is O(1), array.find() is O(n)
  • D. Object/Map is O(n), array.find() is O(1)
Answer: C
C is correct. Object property access and Map.get() are O(1) (constant time). array.find() searches through the array linearly, which is O(n).
MCQ 16
What does (acc[key] || 0) + 1 do in a reduce callback?
  • A. Returns 0 if the key exists
  • B. Sets the count to 1 if the key does not exist, or increments it if it does
  • C. Deletes the key
  • D. Returns the key name
Answer: B
B is correct. If acc[key] is undefined (key does not exist), || 0 gives 0, then + 1 makes it 1. If acc[key] already has a value, it uses that value and adds 1.
MCQ 17
What does array.flat(Infinity) do?
  • A. Creates an infinitely large array
  • B. Flattens all levels of nesting into a single flat array
  • C. Sorts the array infinitely
  • D. Throws an error
Answer: B
B is correct. flat(Infinity) recursively flattens all nested arrays, regardless of depth, into a single flat array.

Coding Challenges

Challenge 1: Student Grade Report

Easy
Given an array of students with name and scores (maths, science, english), calculate each student's average, find the class topper, and list students who scored above 90 in any subject.
Sample Input
[{name: 'Aarav', scores: {maths: 95, science: 88, english: 92}}, ...]
Sample Output
Topper: Aarav (Avg: 91.7) Above 90 in any subject: Aarav, Priya
Use Object.values, reduce, filter, and sort.
const students = [
  { name: "Aarav", scores: { maths: 95, science: 88, english: 92 } },
  { name: "Priya", scores: { maths: 78, science: 95, english: 85 } },
  { name: "Rohan", scores: { maths: 82, science: 76, english: 80 } }
];

const withAvg = students.map(function(s) {
  const vals = Object.values(s.scores);
  const avg = vals.reduce(function(sum, v) { return sum + v; }, 0) / vals.length;
  return { name: s.name, average: Math.round(avg * 10) / 10 };
});

const topper = withAvg.reduce(function(best, s) {
  return s.average > best.average ? s : best;
});
console.log("Topper:", topper.name, "(Avg:", topper.average + ")");

const above90 = students.filter(function(s) {
  return Object.values(s.scores).some(function(v) { return v > 90; });
});
console.log("Above 90:", above90.map(function(s) { return s.name; }).join(", "));

Challenge 2: Word Frequency Counter

Easy
Write a function that takes a string, splits it into words, counts how many times each word appears, and returns the words sorted by frequency (highest first).
Sample Input
"the cat sat on the mat the cat"
Sample Output
the: 3, cat: 2, sat: 1, on: 1, mat: 1
Use split, reduce for counting, Object.entries for sorting.
function wordFrequency(text) {
  const words = text.toLowerCase().split(/\s+/);
  const freq = words.reduce(function(acc, word) {
    acc[word] = (acc[word] || 0) + 1;
    return acc;
  }, {});
  return Object.entries(freq)
    .sort(function(a, b) { return b[1] - a[1]; })
    .map(function([word, count]) { return word + ": " + count; })
    .join(", ");
}
console.log(wordFrequency("the cat sat on the mat the cat"));

Challenge 3: Shopping Cart Calculator

Medium
Given a shopping cart array (items with name, price, quantity, category), write functions to: calculate total, find the most expensive category, get items sorted by total value, and create a summary with item count per category.
Sample Input
[{name: 'Book', price: 300, qty: 2, category: 'Study'}, ...]
Sample Output
Total: Rs 1250 Most expensive category: Electronics Items by value: [...]
Use reduce, sort, Object.entries, and method chaining.
const cart = [
  { name: "Book", price: 300, qty: 2, category: "Study" },
  { name: "Pen", price: 25, qty: 10, category: "Study" },
  { name: "Mouse", price: 500, qty: 1, category: "Electronics" }
];

const total = cart.reduce(function(sum, i) { return sum + i.price * i.qty; }, 0);
console.log("Total: Rs", total);

const byCat = cart.reduce(function(acc, i) {
  acc[i.category] = (acc[i.category] || 0) + i.price * i.qty;
  return acc;
}, {});

const topCat = Object.entries(byCat).sort(function(a, b) { return b[1] - a[1]; })[0];
console.log("Most expensive category:", topCat[0]);

const sorted = [...cart].sort(function(a, b) {
  return (b.price * b.qty) - (a.price * a.qty);
}).map(function(i) { return i.name + ": Rs " + (i.price * i.qty); });
console.log("By value:", sorted);

Challenge 4: Leaderboard System

Medium
Build a leaderboard that sorts players by score (descending), then by wins (descending) for tiebreakers. Add functions to: get top N players, find a player's rank, and calculate the average score of the top 3.
Sample Input
[{name: 'Aarav', score: 920, wins: 12}, ...]
Sample Output
Leaderboard: 1. Priya - 950 (15 wins) 2. Aarav - 920 (12 wins) Aarav's rank: 2
Use sort with multi-criteria comparison. Use findIndex for rank.
const players = [
  { name: "Aarav", score: 920, wins: 12 },
  { name: "Priya", score: 950, wins: 15 },
  { name: "Rohan", score: 920, wins: 14 },
  { name: "Meera", score: 880, wins: 10 }
];

const ranked = [...players].sort(function(a, b) {
  if (b.score !== a.score) return b.score - a.score;
  return b.wins - a.wins;
});

function getTopN(n) {
  return ranked.slice(0, n);
}

function getRank(name) {
  return ranked.findIndex(function(p) { return p.name === name; }) + 1;
}

function topAvg(n) {
  const top = getTopN(n);
  return top.reduce(function(s, p) { return s + p.score; }, 0) / top.length;
}

console.log("Leaderboard:");
ranked.forEach(function(p, i) {
  console.log((i+1) + ". " + p.name + " - " + p.score + " (" + p.wins + " wins)");
});
console.log("Aarav rank:", getRank("Aarav"));
console.log("Top 3 avg:", topAvg(3).toFixed(1));

Challenge 5: Data Transformation Pipeline

Hard
Given raw API data (array of user objects with nested address and posts), write a pipeline that: extracts users from Delhi, flattens their posts into a single array, counts posts per user, sorts by post count, and returns a summary object.
Sample Input
[{name: 'Aarav', address: {city: 'Delhi'}, posts: [{title: 'JS Tips'}, ...]}, ...]
Sample Output
Delhi users: 3, Total posts: 12, Most active: Priya (5 posts)
Use method chaining, flatMap, reduce, sort, and destructuring.
const users = [
  { name: "Aarav", address: { city: "Delhi" }, posts: [{t: "a"}, {t: "b"}, {t: "c"}] },
  { name: "Priya", address: { city: "Delhi" }, posts: [{t: "d"}, {t: "e"}, {t: "f"}, {t: "g"}, {t: "h"}] },
  { name: "Rohan", address: { city: "Mumbai" }, posts: [{t: "i"}] },
  { name: "Meera", address: { city: "Delhi" }, posts: [{t: "j"}, {t: "k"}, {t: "l"}, {t: "m"}] }
];

const delhiUsers = users.filter(function(u) { return u.address.city === "Delhi"; });
const allPosts = delhiUsers.flatMap(function(u) { return u.posts; });
const postCounts = delhiUsers.map(function(u) {
  return { name: u.name, count: u.posts.length };
}).sort(function(a, b) { return b.count - a.count; });

const summary = {
  delhiUsers: delhiUsers.length,
  totalPosts: allPosts.length,
  mostActive: postCounts[0].name + " (" + postCounts[0].count + " posts)"
};
console.log(summary);

Challenge 6: Object Difference Finder

Hard
Write a function that compares two objects and returns an object showing what was added, removed, and changed. Test with user profile updates.
Sample Input
{ name: 'Aarav', age: 15, city: 'Delhi' } vs { name: 'Aarav', age: 16, school: 'DPS' }
Sample Output
{ added: { school: 'DPS' }, removed: { city: 'Delhi' }, changed: { age: { from: 15, to: 16 } } }
Use Object.keys, includes, and reduce.
function objectDiff(oldObj, newObj) {
  const oldKeys = Object.keys(oldObj);
  const newKeys = Object.keys(newObj);
  
  const added = Object.fromEntries(
    newKeys.filter(function(k) { return !oldKeys.includes(k); })
    .map(function(k) { return [k, newObj[k]]; })
  );
  
  const removed = Object.fromEntries(
    oldKeys.filter(function(k) { return !newKeys.includes(k); })
    .map(function(k) { return [k, oldObj[k]]; })
  );
  
  const changed = Object.fromEntries(
    oldKeys.filter(function(k) {
      return newKeys.includes(k) && oldObj[k] !== newObj[k];
    }).map(function(k) {
      return [k, { from: oldObj[k], to: newObj[k] }];
    })
  );
  
  return { added: added, removed: removed, changed: changed };
}

const diff = objectDiff(
  { name: "Aarav", age: 15, city: "Delhi" },
  { name: "Aarav", age: 16, school: "DPS" }
);
console.log(JSON.stringify(diff, null, 2));

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn web development with a live mentor?

Explore our Frontend Masterclass