Top 100 JavaScript Interview Coding Problems
Master JavaScript interviews with 100+ practical coding problems covering arrays, strings, objects, Map/Set, algorithms, and dynamic programming. Learn multiple solution approaches with complexity analysis.
Popular searches this page covers
JavaScript interview questions and answers, JS coding interview questions, array and string problems, object manipulation, map and set questions, two sum, binary search, sorting algorithms, recursion, promises, async/await, and time complexity.
Array Coding Questions (1-30)
1. Reverse an Array
const reverseArray = (arr) => [...arr].reverse();
console.log(reverseArray([1,2,3])); // [3,2,1]
// manual loop
const rev = (arr) => {
const res = [];
for (let i = arr.length-1; i >= 0; i--) res.push(arr[i]);
return res;
};Use built-in reverse or manual loop. spread + reverse avoids mutating original.
2. Find Largest Number
const arr = [5, 2, 9, 1];
const max1 = Math.max(...arr);
const max2 = arr.reduce((a,b)=>a>b?a:b, -Infinity);
let m = arr[0]; for(let x of arr) if(x > m) m = x;
console.log(max1, max2, m);Math.max with spread is concise; reduce or loop works too.
3. Find Smallest Number
const arr = [5, 2, 9, 1];
const min = Math.min(...arr);
// or reduce
const min2 = arr.reduce((a,b)=>a<b?a:b, Infinity);
console.log(min, min2);Math.min or reduce/loop.
4. Remove Duplicates
const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];
// filter/indexOf
const uniq2 = arr.filter((x,i)=>arr.indexOf(x)===i);
console.log(unique, uniq2);Set is simplest O(n); filter is O(n²).
5. Flatten Nested Array
const flat = (arr) => arr.flat(Infinity);
// recursive
const flat2 = a=>a.reduce((r,x)=>r.concat(Array.isArray(x)?flat2(x):x),[]);
console.log(flat([1,[2,3]]), flat2([1,[2,3]]));
flat(Infinity) or recursive reduce.
6. Second Largest Number
const arr = [7, 3, 9, 1, 9, 5];
const arr2 = [...arr];
arr2.sort((a,b)=>b-a);
const second = arr2[1];
// single pass
let max=-Infinity, secondMax=-Infinity;
for(let x of arr){
if(x>max){secondMax=max;max=x;}
else if(x>secondMax && x!==max) secondMax=x;
}
...Sort or one-pass tracking two maximums.
7. Merge Two Arrays Without Duplicates
const a = [1, 2, 3];
const b = [3, 4, 5];
const merge = (a,b)=>[...new Set([...a,...b])];
// using filter
const merge2 = [...a];
b.forEach(x=>{ if(!merge2.includes(x)) merge2.push(x);});
console.log(merge([1,2],[2,3]), merge2);Set union or manual filter inclusion.
8. Sort Array Asc/Desc
let arr1=[3,1,2];
console.log(arr1.sort((a,b)=>a-b)); // asc
console.log(arr1.sort((a,b)=>b-a)); // descUse sort with comparator. Beware mutating original.
9. Sort Array of Objects by Property
let objs=[{age:30,name:'Bob'},{age:20,name:'Alice'}];
console.log(objs.sort((a,b)=>a.age-b.age));
// descending
console.log(objs.sort((a,b)=>b.name.localeCompare(a.name)));Comparator over object fields; use localeCompare for strings.
10. Chunk Array into Smaller Arrays
const chunk = (arr,size)=>{
const res=[];for(let i=0;i<arr.length;i+=size)res.push(arr.slice(i,i+size));return res;};
console.log(chunk([1,2,3,4,5],2));Slice in loop or reduce-based approach.
11. Rotate Array Left by k Positions
const rotateLeft=(arr,k)=>{
k=k%arr.length;return arr.slice(k).concat(arr.slice(0,k));};
console.log(rotateLeft([1,2,3,4],2));Use slice and concat or reverse technique.
12. Rotate Array Right by k Positions
const rotateRight=(arr,k)=>{
k=k%arr.length;return arr.slice(-k).concat(arr.slice(0,-k));};
console.log(rotateRight([1,2,3,4],2));Mirror of left rotation.
13. Find Intersection of Two Arrays
const intersection=(a,b)=>[...new Set(a)].filter(x=>new Set(b).has(x));
console.log(intersection([1,2,3],[2,3,4]));
Use Set for membership check.
14. Find Difference Between Two Arrays
const difference=(a,b)=>a.filter(x=>!new Set(b).has(x));
console.log(difference([1,2,3],[2,3]));Filter those not in second set.
15. Check if Array Contains Duplicates
const hasDup=arr=>new Set(arr).size!==arr.length;
console.log(hasDup([1,2,2]), hasDup([1,2,3]));
Compare set size with length.
16. Find Missing Number in Array
const missing=(arr)=>{
const n=arr.length;return (n*(n+1))/2 - arr.reduce((a,b)=>a+b,0);
};
console.log(missing([1,2,4,5]));Use formula or XOR approach.
17. Remove Falsy Values from Array
const compact=arr=>arr.filter(Boolean);
console.log(compact([0,1,false,2,'',3]));Filter with Boolean to remove false,0,'',null,undefined,NaN.
18. Find Frequency of Elements in Array
const freq=arr=>arr.reduce((m,x)=>(m[x]= (m[x]||0)+1,m),{});
console.log(freq([1,2,2,3]));Use reduce to build frequency map.
19. Convert Array to Object
const toObj=arr=>Object.assign({},arr);
// or with keys
const toObj2=(arr,keys)=>Object.fromEntries(arr.map((v,i)=>[keys[i],v]));
console.log(toObj(["a","b"]));
console.log(toObj2([1,2],["x","y"]));Assign or fromEntries with keys.
20. Convert Array of Objects to Single Object
// assume [{k:1,v:2},{k:3,v:4}]
const arrToObj = arr=>Object.fromEntries(arr.map(o=>[o.k,o.v]));
console.log(arrToObj([{k:1,v:2},{k:3,v:4}]));Use fromEntries after mapping.
21. Group Array Objects by Property
const groupBy=(arr,key)=>arr.reduce((r,o)=>{(r[o[key]]||(r[o[key]]=[])).push(o);return r;},{});
console.log(groupBy([{type:'a',val:1},{type:'b',val:2},{type:'a',val:3}], 'type'));Use reduce to bucket by key.
22. Sum All Numbers in Array
const sum=arr=>arr.reduce((a,b)=>a+b,0);
console.log(sum([1,2,3,4]));Simple reduce sum.
23. Find Pairs with Given Sum (Two Sum)
// map-based
const pairs=(arr,target)=>{
const m=new Map();const res=[];
for(let x of arr){
if(m.has(target-x))res.push([target-x,x]);
m.set(x,true);
}
return res;
};
console.log(pairs([1,2,3,4],5));Use map to record seen numbers.
24. Remove Specific Element from Array
const removeElem=(arr,val)=>arr.filter(x=>x!==val);
console.log(removeElem([1,2,3,2],2));Filter out unwanted value.
25. Shuffle an Array Randomly
const shuffle=(arr)=>{
for(let i=arr.length-1;i>0;i--){
const j=Math.floor(Math.random()*(i+1));
[arr[i],arr[j]]=[arr[j],arr[i]];
}
return arr;
};
console.log(shuffle([1,2,3,4,5]));Fisher–Yates shuffle for uniform randomness.
26. Maximum Sum Subarray (Kadane’s Algorithm)
const maxSubArray=(arr)=>{
let maxSoFar=arr[0],maxEnding=arr[0];
for(let i=1;i<arr.length;i++){
maxEnding=Math.max(arr[i],maxEnding+arr[i]);
maxSoFar=Math.max(maxSoFar,maxEnding);
}
return maxSoFar;
};
console.log(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]));Kadane's algorithm O(n) time.
27. Move All Zeros to End of Array
const moveZeros=(arr)=>{
const res=arr.filter(x=>x!==0);
return res.concat(Array(arr.length-res.length).fill(0));
};
console.log(moveZeros([0,1,0,3,12]));Filter zeros and append. In-place two-pointer also possible.
28. Flatten Array Using Recursion
const flatten=(arr)=>arr.reduce((a,x)=>a.concat(Array.isArray(x)?flatten(x):x),[]);
console.log(flatten([1,[2,[3]]]));Recursive reduce flatten.
29. Implement Custom map()
Array.prototype.myMap = function(fn) {
const res=[];
for(let i=0;i<this.length;i++){
res.push(fn(this[i],i,this));
}
return res;
};
console.log([1,2,3].myMap(x=>x*2));Polyfill for map using loop.
30. Implement Custom filter()
Array.prototype.myFilter = function(fn) {
const res=[];
for(let i=0;i<this.length;i++){
if(fn(this[i],i,this)) res.push(this[i]);
}
return res;
};
console.log([1,2,3,4].myFilter(x=>x%2===0));Polyfill for filter using loop.
String Coding Questions (31-55)
31. Reverse a String
const reverse = s=>s.split('').reverse().join('');
console.log(reverse('hello'));Split/join or loop.
32. Check if String is Palindrome
const isPal = s => s===s.split('').reverse().join('');
console.log(isPal('racecar'), isPal('hello'));Compare with reversed string.
33. Count Vowels in a String
const countVowels = s => (s.match(/[aeiou]/gi)||[]).length;
console.log(countVowels('beautiful'));Regex match.
34. Count Consonants in a String
const countCons = s => (s.match(/[^aeiouWd_]/gi)||[]).length;
console.log(countCons('hello world'));Regex excluding vowels and non-letters.
35. Capitalize First Letter of Each Word
const titleCase = s => s.split(' ').map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join(' ');
console.log(titleCase('hello world'));Split on spaces and upper-case first char.
36. Find Longest Word in String
const longest = s=>s.split(' ').reduce((a,b)=>b.length>a.length?b:a,"");
console.log(longest('find the longest word in this sentence'));Split and reduce by length.
37. Remove Duplicate Characters from String
const uniq = s=>[...new Set(s)].join('');
console.log(uniq('banana'));Use Set to filter duplicates.
38. Check if Two Strings are Anagrams
const isAnagram=(a,b)=>a.split('').sort().join('')===b.split('').sort().join('');
console.log(isAnagram('listen','silent'), isAnagram('hello','world'));Sort both strings to compare.
39. Find First Non-Repeating Character
const firstNonRepeat = s => {
for(let i=0;i<s.length;i++) if(s.indexOf(s[i])===s.lastIndexOf(s[i])) return s[i];
return null;
};
console.log(firstNonRepeat('swiss'));Loop and check index positions.
40. Find Most Frequent Character in String
const mostFreq = s => {
const m={}; for(let c of s)m[c]=(m[c]||0)+1;
return Object.keys(m).reduce((a,b)=>m[a]>m[b]?a:b);
};
console.log(mostFreq('programming'));Build frequency map.
41. Reverse Words in a Sentence
const revWords = s=>s.split(' ').reverse().join(' ');
console.log(revWords('hello world from js'));Split by spaces, reverse array.
42. Check if String Contains Only Numbers
const isNum = s=>/^d+$/.test(s);
console.log(isNum('12345'), isNum('123a'));Regex digit-only.
43. Check if String Contains Only Alphabets
const isAlpha = s=>/^[a-zA-Z]+$/.test(s);
console.log(isAlpha('Hello'), isAlpha('Hello123'));Regex letters-only.
44. Truncate String with Ellipsis
const truncate=(s,n)=>s.length>n? s.slice(0,n-3)+'...':s;
console.log(truncate('This is a long string',10));Slice and append ellipsis if too long.
45. Convert snake_case to camelCase
const toCamel = s=>s.replace(/_([a-z])/g,(m,p)=>p.toUpperCase());
console.log(toCamel('hello_world'));Use regex replace.
46. Convert camelCase to snake_case
const toSnake = s=>s.replace(/([A-Z])/g,'_$1').toLowerCase();
console.log(toSnake('helloWorld'));Insert underscore before capitals.
47. Repeat String n Times
const repeat = (s,n)=>s.repeat(n);
console.log(repeat('ha',3));Use built-in repeat.
48. Check if String Starts with Substring
const starts = (s,sub)=>s.indexOf(sub)===0;
console.log(starts('javascript','java'));Use startsWith or indexOf.
49. Check if String Ends with Substring
const ends = (s,sub)=>s.slice(-sub.length)===sub;
console.log(ends('javascript','script'));Use endsWith or slice.
50. Remove Spaces from String
const removeSpaces = s=>s.replace(/s+/g,'');
console.log(removeSpaces('a b c'));Regex to remove whitespace.
51. Count Occurrences of Substring
const countSub=(s,sub)=>s.split(sub).length-1;
console.log(countSub('hellohello','hello'));Split by substring.
52. Replace All Occurrences of Substring
const replaceAll=(s,find,rep)=>s.split(find).join(rep);
console.log(replaceAll('foo foo foo','foo','bar'));Split and join as alternative to regex.
53. Check if String is Valid Email
const isEmail = s=>/^[^s@]+@[^s@]+.[^s@]+$/.test(s);
console.log(isEmail('test@example.com'), isEmail('bad@com'));Simple regex email validation.
54. Convert String to Title Case
const titleCase = s=>s.toLowerCase().split(' ').map(w=>w.replace(/^[a-z]/,c=>c.toUpperCase())).join(' ');
console.log(titleCase('hello world'));Lowercases then capitalizes each word.
55. Generate Random String
const randStr = len => Math.random().toString(36).substring(2,2+len);
console.log(randStr(8));Use base36 representation of random number.
Object Coding Questions (56-75)
56. Deep Clone an Object
const deepClone = obj => JSON.parse(JSON.stringify(obj));
// or recursive
function clone(o){
if(o===null||typeof o!=='object') return o;
if(Array.isArray(o)) return o.map(clone);
const res={};
for(let k in o) res[k]=clone(o[k]);
return res;
}
const original={a:1,b:{c:2}};
...JSON methods or recursive function. Beware functions and dates.
57. Merge Two Objects
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = {...obj1, ...obj2};
// or Object.assign({},obj1,obj2);
console.log({...{a:1},{b:2}});Spread or assign; later properties override.
58. Check if Object is Empty
const isEmpty = obj => Object.keys(obj).length===0;
console.log(isEmpty({}), isEmpty({a:1}));Keys length zero means empty.
59. Convert Object to Array
const obj = { x: 1, y: 2 };
const arr = Object.entries(obj);
// values only: Object.values(obj);
console.log(arr, Object.values(obj));entries, keys, or values.
60. Convert Array to Object Using Key
const toObj = arr => Object.fromEntries(arr.map(o=>[o.id,o]));
console.log(toObj([{id:'a',val:1},{id:'b',val:2}]));Use fromEntries with chosen key.
61. Get Nested Property Safely
const get = (obj,path)=>path.split('.').reduce((o,k)=>o?o[k]:undefined,obj);
console.log(get({a:{b:2}},'a.b'), get({a:{b:2}},'a.c'));Reduce through path. Optional chaining also works.
62. Flatten Nested Object
const flattenObj = (obj, pref='') =>
Object.keys(obj).reduce((res,k)=>{
const val=obj[k];
const key=pref?pref+'.'+k:k;
if(typeof val==='object'&&val!==null) Object.assign(res,flattenObj(val,key));
else res[key]=val;
return res;
},{});
console.log(flattenObj({a:{b:1},c:2}));
Recursive flatten with dot notation keys.
63. Count Number of Keys in Object
const count= obj => Object.keys(obj).length;
console.log(count({a:1,b:2}));Simple keys length.
64. Remove Property from Object
const removeKey=(obj,key)=>{
const {[key]:_,...rest}=obj; return rest;
};
console.log(removeKey({a:1,b:2},'a'));Destructure to exclude key.
65. Find Difference Between Two Objects
const diff=(a,b)=>{
const res={};
for(let k in a) if(a[k]!==b[k]) res[k]=a[k];
return res;
};
console.log(diff({a:1,b:2},{a:1,b:3}));Compare values and capture mismatches from first object.
66. Check if Two Objects are Equal
const eq = (a,b)=>JSON.stringify(a)===JSON.stringify(b);
console.log(eq({x:1},{x:1}), eq({x:1},{x:2}));Simple string comparison; not reliable for functions/order.
67. Group Objects by Property
const groupBy=(arr,key)=>arr.reduce((r,o)=>{(r[o[key]]||(r[o[key]]=[])).push(o);return r;},{});
console.log(groupBy([{type:'a'},{type:'b'},{type:'a'}],'type'));Same as earlier array grouping but for objects.
68. Convert Object Values to Array
const vals = obj => Object.values(obj);
console.log(vals({a:1,b:2}));Built-in values method.
69. Swap Keys and Values in Object
const swap = obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[v,k]));
console.log(swap({a:1,b:2}));Use entries map.
70. Get Unique Values from Object Array
const unique=arr=>[...new Set(arr.map(o=>o.value))];
console.log(unique([{value:1},{value:2},{value:1}]));Map property then Set.
71. Sort Object by Values
const sortByValue = obj => Object.fromEntries(
Object.entries(obj).sort((a,b)=>a[1]-b[1])
);
console.log(sortByValue({a:2,b:1,c:3}));Sort entries then back to object.
72. Remove Undefined Properties from Object
const clean = obj=>Object.fromEntries(
Object.entries(obj).filter(([k,v])=>v!==undefined)
);
console.log(clean({a:1,b:undefined,c:2}));Filter entries where value !== undefined.
73. Pick Specific Keys from Object
const pick=(obj,keys)=>Object.fromEntries(
keys.map(k=>[k,obj[k]])
);
console.log(pick({a:1,b:2,c:3},['a','c']));Create object with selected keys.
74. Omit Specific Keys from Object
const omit=(obj,keys)=>Object.fromEntries(
Object.entries(obj).filter(([k])=>!keys.includes(k))
);
console.log(omit({a:1,b:2,c:3},['b']));Filter out unwanted keys.
75. Implement Object Deep Freeze
const deepFreeze = obj => {
Object.freeze(obj);
Object.keys(obj).forEach(k=>{
if(typeof obj[k]==="object" && obj[k]!==null) deepFreeze(obj[k]);
});
return obj;
};
const o={a:1,b:{c:2}};deepFreeze(o); o.b.c=3; console.log(o);Recursively freeze all nested objects.
Set Coding Questions (76-85)
76. Remove Duplicates Using Set
const arr = [1, 2, 2, 3];
const uniq=[...new Set(arr)];
console.log(uniq);Simple set conversion.
77. Find Union of Two Sets
const union=(a,b)=>new Set([...a,...b]);
console.log(union(new Set([1,2]), new Set([2,3])));Spread into new Set.
78. Find Intersection of Two Sets
const inter=(a,b)=>new Set([...a].filter(x=>b.has(x)));
console.log(inter(new Set([1,2]), new Set([2,3])));Filter membership.
79. Find Difference Between Sets
const diff=(a,b)=>new Set([...a].filter(x=>!b.has(x)));
console.log(diff(new Set([1,2,3]), new Set([2])));Filter not in second.
80. Check if Set Contains Value
const has=(s,v)=>s.has(v);
console.log(has(new Set([1,2,3]),2));Use has method.
81. Convert Set to Array
const s = new Set([1, 2, 3]);
const arr=[...s];
console.log(arr);Spread into array.
82. Count Unique Elements Using Set
const arr = [1, 2, 2, 3];
const count= new Set(arr).size;
console.log(count);Size property.
83. Remove Duplicates from String Using Set
const str = "banana";
const uniqStr=[...new Set(str)].join('');
console.log(uniqStr);Convert to set then join.
84. Find Common Elements Between Arrays Using Set
const common=(a,b)=>[...new Set(a)].filter(x=>new Set(b).has(x));
console.log(common([1,2,3],[2,3,4]));Intersection via sets.
85. Check if Array Elements Are Unique
const unique=arr=>new Set(arr).size===arr.length;
console.log(unique([1,2,2]), unique([1,2,3]));Compare sizes.
Map Coding Questions (86-95)
86. Count Frequency Using Map
const freq=(arr)=>{
const m=new Map();
arr.forEach(x=>m.set(x,(m.get(x)||0)+1));
return m;
};
console.log(freq([1,2,2,3]));Map stores counts.
87. Group Array Elements Using Map
const group=(arr,key)=>{
const m=new Map();
arr.forEach(o=>{
const k=o[key];
if(!m.has(k)) m.set(k,[]);
m.get(k).push(o);
});
return m;
};
console.log(group([{id:1,cat:'a'},{id:2,cat:'b'},{id:3,cat:'a'}],'cat'));Map buckets by key.
88. Convert Object to Map
const obj = { a: 1, b: 2 };
const map=new Map(Object.entries(obj));
console.log(map);Entries to Map constructor.
89. Convert Map to Object
const map = new Map([['a',1],['b',2]]);
const obj=Object.fromEntries(map);
console.log(obj);fromEntries with Map.
90. Implement Caching Using Map
const cache=new Map();
function memo(fn){
return function(arg){
if(cache.has(arg)) return cache.get(arg);
const res=fn(arg);
cache.set(arg,res);
return res;
};
}
const square=memo(x=>x*x);
...Simple memoization.
91. Find Duplicate Elements Using Map
const duplicates=(arr)=>{
const m=new Map();
arr.forEach(x=>m.set(x,(m.get(x)||0)+1));
return [...m.entries()].filter(([k,v])=>v>1).map(([k])=>k);
};
console.log(duplicates([1,2,2,3,3,3]));Use map to count then filter.
92. Count Character Frequency in String Using Map
const charFreq=s=>{
const m=new Map();
for(let c of s) m.set(c,(m.get(c)||0)+1);
return m;
};
console.log(charFreq('abbc'));Map counts characters.
93. Store User Sessions Using Map
const sessions=new Map();
function createSession(id,data){sessions.set(id,data);}
function getSession(id){return sessions.get(id);}
createSession('u1',{name:'Alice'});
console.log(getSession('u1'));Map works as in-memory store.
94. Implement LRU Cache Using Map
class LRU {
constructor(limit=5){this.limit=limit;this.map=new Map();}
get(key){
if(!this.map.has(key)) return null;
const val=this.map.get(key);
this.map.delete(key);
this.map.set(key,val);
return val;
}
put(key,val){
...Map preserves insertion order; delete+set moves to end.
95. Merge Two Maps
const mergeMaps=(m1,m2)=>new Map([...m1,...m2]);
console.log(mergeMaps(new Map([[1,'a']]), new Map([[2,'b']])));Spread entries.
Common Frontend Utility Coding Questions (96-100)
96. Implement Debounce Function
function debounce(fn,delay){
let timer;
return function(...args){
clearTimeout(timer);
timer=setTimeout(()=>fn.apply(this,args),delay);
};
}
const debounced = debounce(x=>console.log('called',x),100);
debounced(1);
debounced(2);Delays invocation until after delay.
97. Implement Throttle Function
function throttle(fn,limit){
let inThrottle;
return function(...args){
if(!inThrottle){
fn.apply(this,args);
inThrottle=true;
setTimeout(()=>inThrottle=false,limit);
}
};
}
...Allows call at most once per limit.
98. Implement Deep Equality Check
function deepEqual(a,b){
if(a===b) return true;
if(typeof a!="object"||typeof b!="object"||a==null||b==null) return false;
const ka=Object.keys(a), kb=Object.keys(b);
if(ka.length!==kb.length) return false;
for(let k of ka){
if(!deepEqual(a[k],b[k])) return false;
}
return true;
}
...Recursive comparison of properties.
99. Implement Custom reduce()
Array.prototype.myReduce=function(fn,initial){
let acc=initial!==undefined?initial:this[0];
let start=initial!==undefined?0:1;
for(let i=start;i<this.length;i++) acc=fn(acc,this[i],i,this);
return acc;
};
console.log([1,2,3].myReduce((a,b)=>a+b,0));Simple reduce polyfill.
100. Implement Promise.all()
function promiseAll(promises){
return new Promise((resolve,reject)=>{
const results=[];let count=0;
promises.forEach((p,i)=>{
Promise.resolve(p).then(r=>{
results[i]=r;count++;
if(count===promises.length) resolve(results);
}).catch(reject);
});
});
...Collects all results, rejects on first failure.