Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views9 pages

JS Coding Questions CompanyWise With JSON

code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

JS Coding Questions CompanyWise With JSON

code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

JavaScript Interview Coding Questions

(Company-Wise)
Google

Reverse words in a sentence


function reverseWords(str) {
return str.split(" ").reverse().join(" ");
}

Implement debounce function


function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}

Deep clone an object


function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}

Find unique elements in two arrays


function uniqueElements(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}

Implement Promise.all polyfill


Promise.myAll = function(promises) {
return new Promise((resolve, reject) => {
let results = [], completed = 0;
promises.forEach((p, i) => {
Promise.resolve(p).then(val => {
results[i] = val;
completed++;
if(completed === promises.length) resolve(results);
}).catch(reject);
});
});
};
Find longest common prefix
function longestCommonPrefix(strs) {
if (!strs.length) return "";
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.slice(0, -1);
if (!prefix) return "";
}
}
return prefix;
}

Check if string is valid parentheses


function isValid(s) {
let stack = [], map = {")":"(", "}":"{", "]":"["};
for(let ch of s){
if(ch in map){
if(stack.pop() !== map[ch]) return false;
} else stack.push(ch);
}
return !stack.length;
}

Two Sum problem


function twoSum(nums, target) {
let map = new Map();
for(let i=0;i<nums.length;i++){
let diff = target - nums[i];
if(map.has(diff)) return [map.get(diff), i];
map.set(nums[i], i);
}
}

Implement once function


function once(fn) {
let called = false, result;
return function(...args) {
if (!called) {
result = fn.apply(this, args);
called = true;
}
return result;
}
}
Shuffle an array
function shuffle(arr) {
for(let i=arr.length-1;i>0;i--){
let j=Math.floor(Math.random()*(i+1));
[arr[i], arr[j]]=[arr[j], arr[i]];
}
return arr;
}

Amazon

First non-repeating character in string


function firstUniqueChar(str) {
let count = {};
for (let char of str) count[char] = (count[char]||0)+1;
for (let char of str) if (count[char] === 1) return char;
return null;
}

Rotate array by k steps


function rotate(arr, k) {
k = k % arr.length;
return arr.slice(-k).concat(arr.slice(0, -k));
}

Longest substring without repeating characters


function lengthOfLongestSubstring(s) {
let set = new Set(), left = 0, maxLen = 0;
for(let right=0; right<s.length; right++){
while(set.has(s[right])) set.delete(s[left++]);
set.add(s[right]);
maxLen = Math.max(maxLen, right-left+1);
}
return maxLen;
}

Implement throttling
function throttle(fn, delay) {
let last = 0;
return function(...args){
let now = Date.now();
if(now - last >= delay){
fn.apply(this, args);
last = now;
}
};
}
Find intersection of two arrays
function intersect(arr1, arr2) {
let set = new Set(arr1);
return arr2.filter(x => set.has(x));
}

Maximum subarray sum (Kadane's Algorithm)


function maxSubArray(nums) {
let max=nums[0], curr=nums[0];
for(let i=1;i<nums.length;i++){
curr=Math.max(nums[i], curr+nums[i]);
max=Math.max(max,curr);
}
return max;
}

Move zeros to end


function moveZeroes(nums) {
let idx=0;
for(let num of nums){
if(num!==0) nums[idx++]=num;
}
while(idx<nums.length) nums[idx++]=0;
return nums;
}

Group anagrams
function groupAnagrams(strs) {
let map = {};
for(let s of strs){
let key = s.split("").sort().join("");
if(!map[key]) map[key]=[];
map[key].push(s);
}
return Object.values(map);
}

Find majority element


function majorityElement(nums) {
let count=0, candidate=null;
for(let num of nums){
if(count===0) candidate=num;
count += (num===candidate)?1:-1;
}
return candidate;
}
Merge intervals
function merge(intervals) {
intervals.sort((a,b)=>a[0]-b[0]);
let res=[intervals[0]];
for(let i=1;i<intervals.length;i++){
let prev=res[res.length-1];
if(intervals[i][0]<=prev[1]) prev[1]=Math.max(prev[1], intervals[i]
[1]);
else res.push(intervals[i]);
}
return res;
}

Microsoft

Implement setTimeout using setInterval


function mySetTimeout(callback, delay) {
let interval = setInterval(() => {
callback();
clearInterval(interval);
}, delay);
}

Merge two sorted arrays


function mergeSorted(arr1, arr2) {
let res = [], i=0, j=0;
while(i<arr1.length && j<arr2.length){
if(arr1[i]<arr2[j]) res.push(arr1[i++]);
else res.push(arr2[j++]);
}
return res.concat(arr1.slice(i)).concat(arr2.slice(j));
}

Flatten nested object


function flattenObj(obj, parent="", res={}) {
for(let key in obj){
let newKey = parent?parent+"."+key:key;
if(typeof obj[key]==="object") flattenObj(obj[key], newKey, res);
else res[newKey]=obj[key];
}
return res;
}

Implement async/await using promises


function asyncFn() {
return new Promise(resolve => setTimeout(()=>resolve("done"),1000));
}
(async ()=>{
let res = await asyncFn();
console.log(res);
})();

Find missing number from 1..n


function missingNumber(nums) {
let n=nums.length, total=(n*(n+1))/2;
let sum=nums.reduce((a,b)=>a+b,0);
return total-sum;
}

Meta (Facebook)

Currying function
function curry(fn) {
return function curried(...args){
if(args.length>=fn.length) return fn.apply(this,args);
return (...next)=>curried.apply(this,args.concat(next));
};
}

Memoization function
function memoize(fn) {
let cache={};
return function(x){
if(x in cache) return cache[x];
return cache[x]=fn(x);
}
}

Polyfill for map


Array.prototype.myMap = function(cb) {
let res=[];
for(let i=0;i<this.length;i++) res.push(cb(this[i],i,this));
return res;
}

Polyfill for filter


Array.prototype.myFilter = function(cb) {
let res=[];
for(let i=0;i<this.length;i++) if(cb(this[i],i,this))
res.push(this[i]);
return res;
}
Polyfill for reduce
Array.prototype.myReduce = function(cb, init) {
let acc=init;
for(let i=0;i<this.length;i++) acc=cb(acc,this[i],i,this);
return acc;
}

Infosys/TCS/Wipro

Factorial of number
function factorial(n) {
if(n===0) return 1;
return n*factorial(n-1);
}

Check Palindrome
function isPalindrome(str) {
return str===str.split("").reverse().join("");
}

Find GCD of two numbers


function gcd(a,b){
return b===0?a:gcd(b,a%b);
}

Check Armstrong number


function isArmstrong(num){
let str=num.toString();
let sum=0;
for(let ch of str) sum+=Math.pow(+ch,str.length);
return sum===num;
}

Count vowels in a string


function countVowels(str){
return (str.match(/[aeiou]/gi)||[]).length;
}

JSON Coding Questions

Parse a JSON string into an object


let jsonStr = '{"name":"Kishore","age":23}';
let obj = JSON.parse(jsonStr);
console.log(obj.name); // Kishore
Convert object into JSON string
let user = { name: "Kishore", age: 23 };
let jsonStr = JSON.stringify(user);
console.log(jsonStr); // {"name":"Kishore","age":23}

Pretty-print JSON
let user = { name: "Kishore", age: 23, skills: ["JS","React"] };
console.log(JSON.stringify(user, null, 2));

Deep clone using JSON


let obj = { a: 1, b: { c: 2 } };
let clone = JSON.parse(JSON.stringify(obj));
clone.b.c = 99;
console.log(obj.b.c); // 2
console.log(clone.b.c); // 99

Handle circular JSON safely


let obj = { name: "A" };
obj.self = obj;
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return;
seen.add(value);
}
return value;
});
}
console.log(safeStringify(obj)); // {"name":"A"}

Extract values from JSON array


let data = '[{"id":1,"name":"Apple"},{"id":2,"name":"Mango"}]';
let arr = JSON.parse(data);
let names = arr.map(item => item.name);
console.log(names); // ["Apple", "Mango"]

Merge two JSON objects


let obj1 = { a: 1, b: 2 };
let obj2 = { b: 3, c: 4 };
let merged = { ...obj1, ...obj2 };
console.log(merged); // {a:1, b:3, c:4}

Filter JSON data


let users = [
{ name: "Kishore", age: 23 },
{ name: "Vijay", age: 30 }
];
let youngUsers = users.filter(u => u.age < 25);
console.log(youngUsers); // [{ name:"Kishore", age:23 }]

Convert JSON array to CSV


let users = [
{ name: "Kishore", age: 23 },
{ name: "Vijay", age: 30 }
];
let keys = Object.keys(users[0]);
let csv = [keys.join(",")].concat(users.map(u => keys.map(k =>
u[k]).join(","))).join("\n");
console.log(csv);

Safely access nested JSON properties


let data = { user: { profile: { email: "[email protected]" } } };
console.log(data?.user?.profile?.email); // [email protected]
console.log(data?.user?.address?.city); // undefined

You might also like