Transform data cleanly
Most JavaScript coding questions are data transformations. Use Set, Map, reduce and recursion deliberately, and state edge cases and complexity.
- ArraysChunk, unique, pairs and grouping.
- ObjectsFlatten and deep equality.
- StringsTitle case, frequency and Roman numerals.
Front-end and full-stack coding rounds ask you to transform data quickly and correctly in plain JavaScript. These solutions use modern, readable JavaScript and note the time complexity — the style interviewers like to see.
1. Split an array into chunks of a given size.
Step through the array by the chunk size and slice. O(n).
const chunk = (arr, size) => {
const out = [];
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
return out;
};
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]2. Flatten a nested object into dotted keys.
Recurse into plain objects, carrying the key path. Arrays and dates are kept as values here — mention that choice.
function flattenObject(obj, prefix = '', out = {}) {
for (const [key, value] of Object.entries(obj)) {
const path = prefix ? `${prefix}.${key}` : key;
if (value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
flattenObject(value, path, out);
} else {
out[path] = value;
}
}
return out;
}
flattenObject({ user: { name: 'Asha', address: { city: 'Pune' } }, active: true });
// { 'user.name': 'Asha', 'user.address.city': 'Pune', active: true }3. Group an array of objects by a key.
Use Object.groupBy where available, or reduce.
const orders = [{ id: 1, city: 'Pune' }, { id: 2, city: 'Delhi' }, { id: 3, city: 'Pune' }];
const byCity = Object.groupBy(orders, o => o.city); // modern runtimes
const byCity2 = orders.reduce((acc, o) => {
(acc[o.city] ??= []).push(o);
return acc;
}, {});4. Write a deep equality check.
Compare primitives directly; for objects, compare key counts and recurse into each key. Handle arrays, null and NaN.
function deepEqual(a, b) {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
const keysA = Object.keys(a), keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every(k => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
}5. Return unique values, and unique objects by id.
A Set removes duplicate primitives; a Map keyed by id keeps one object per id (the last one wins).
const uniqueNums = [...new Set([3, 1, 3, 2, 1])]; // [3, 1, 2]
const uniqueUsers = [...new Map(users.map(u => [u.id, u])).values()];6. Find all pairs that add up to a target.
One pass with a Set of seen numbers — O(n).
function pairsWithSum(nums, target) {
const seen = new Set(), pairs = [];
for (const n of nums) {
if (seen.has(target - n)) pairs.push([target - n, n]);
seen.add(n);
}
return pairs;
}
pairsWithSum([2, 7, 4, 5, 11], 9); // [[2, 7], [4, 5]]7. Capitalise the first letter of each word and count word frequency.
String and array methods together; normalise case before counting.
const titleCase = s => s.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
titleCase('learn frenzy interview prep'); // 'Learn Frenzy Interview Prep'
const wordFreq = text => text.toLowerCase().match(/[a-z']+/g)
.reduce((acc, w) => ((acc[w] = (acc[w] ?? 0) + 1), acc), {});8. Convert a number to Roman numerals.
Walk a table of values from largest to smallest, subtracting while possible. Including 900, 400, 90, 40, 9 and 4 handles the subtractive forms.
function toRoman(num) {
const table = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'],
[50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']];
let out = '';
for (const [value, symbol] of table) {
while (num >= value) { out += symbol; num -= value; }
}
return out;
}
toRoman(2026); // 'MMXXVI'Remember
Key points
- Set for uniqueness
Map for unique-by-key.
- Object.is handles NaN
Useful in equality checks.
- ??= for grouping
Create arrays on first use.
- Greedy tables
Roman numerals and coin-like problems.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 Find the intersection of two arrays. Basic
Put one array in a Set and filter the other:
a.filter(x => setB.has(x))— O(n + m). -
2 Check whether two strings are anagrams. Basic
Compare character counts in a Map, or compare sorted strings.
-
3 Implement Array.prototype.flat for one level. Basic
arr.reduce((acc, x) => acc.concat(x), []). -
4 Find the most frequent element. Basic
Count in a Map, then pick the entry with the highest count.
-
5 Sort an array of objects by two keys. Intermediate
Compare the first key and fall back to the second:
(a, b) => a.city.localeCompare(b.city) || b.score - a.score. -
6 Convert a query string to an object. Basic
Object.fromEntries(new URLSearchParams('a=1&b=2')).