DEV Community

Jeya Lakshmi
Jeya Lakshmi

Posted on

javascript code

// ========================================
// 50 JavaScript Technical Questions
// ========================================

// 1. Reverse a String
// Input: "hello"
// Output: "olleh"
function reverseString(str) {
return str.split('').reverse().join('');
}

// 2. Check if Palindrome
// Input: "racecar"
// Output: true
function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
}

// 3. Find Largest Number in Array
// Input: [3, 7, 2, 9, 1]
// Output: 9
function findLargest(arr) {
return Math.max(...arr);
}

// 4. Sum of Array Elements
// Input: [1, 2, 3, 4, 5]
// Output: 15
function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}

// 5. Count Vowels in String
// Input: "hello world"
// Output: 3
function countVowels(str) {
return (str.match(/[aeiou]/gi) || []).length;
}

// 6. Factorial of Number
// Input: 5
// Output: 120
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}

// 7. Fibonacci Sequence
// Input: 7
// Output: [0, 1, 1, 2, 3, 5, 8]
function fibonacci(n) {
const fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib.slice(0, n);
}

// 8. Remove Duplicates from Array
// Input: [1, 2, 2, 3, 4, 4, 5]
// Output: [1, 2, 3, 4, 5]
function removeDuplicates(arr) {
return [...new Set(arr)];
}

// 9. Check if Prime Number
// Input: 17
// Output: true
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}

// 10. Find Missing Number in Array
// Input: [1, 2, 4, 5, 6]
// Output: 3
function findMissing(arr) {
const n = arr.length + 1;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = arr.reduce((a, b) => a + b, 0);
return expectedSum - actualSum;
}

// 11. Capitalize First Letter of Each Word
// Input: "hello world"
// Output: "Hello World"
function capitalizeWords(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
}

// 12. Flatten Nested Array
// Input: [1, [2, [3, 4], 5], 6]
// Output: [1, 2, 3, 4, 5, 6]
function flattenArray(arr) {
return arr.flat(Infinity);
}

// 13. Find Second Largest Number
// Input: [3, 7, 2, 9, 1, 8]
// Output: 8
function secondLargest(arr) {
const unique = [...new Set(arr)].sort((a, b) => b - a);
return unique[1];
}

// 14. Anagram Check
// Input: "listen", "silent"
// Output: true
function isAnagram(str1, str2) {
const sort = str => str.toLowerCase().split('').sort().join('');
return sort(str1) === sort(str2);
}

// 15. Merge Two Sorted Arrays
// Input: [1, 3, 5], [2, 4, 6]
// Output: [1, 2, 3, 4, 5, 6]
function mergeSorted(arr1, arr2) {
return [...arr1, ...arr2].sort((a, b) => a - b);
}

// 16. Count Character Occurrences
// Input: "hello", "l"
// Output: 2
function countChar(str, char) {
return str.split('').filter(c => c === char).length;
}

// 17. Find Longest Word in String
// Input: "The quick brown fox"
// Output: "quick"
function longestWord(str) {
const words = str.split(' ');
return words.reduce((longest, word) => word.length > longest.length ? word : longest, '');
}

// 18. Reverse Words in String
// Input: "Hello World"
// Output: "World Hello"
function reverseWords(str) {
return str.split(' ').reverse().join(' ');
}

// 19. Calculate Power
// Input: 2, 3
// Output: 8
function power(base, exp) {
return Math.pow(base, exp);
}

// 20. Check if Array is Sorted
// Input: [1, 2, 3, 4, 5]
// Output: true
function isSorted(arr) {
return arr.every((val, i) => i === 0 || val >= arr[i - 1]);
}

// 21. Find Index of Element
// Input: [10, 20, 30, 40], 30
// Output: 2
function findIndex(arr, element) {
return arr.indexOf(element);
}

// 22. Generate Random Number in Range
// Input: 1, 10
// Output: (random number between 1-10)
function randomInRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 23. Check if Object is Empty
// Input: {}
// Output: true
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}

// 24. Deep Clone Object
// Input: {a: 1, b: {c: 2}}
// Output: {a: 1, b: {c: 2}}
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}

// 25. Convert String to Title Case
// Input: "hello world from javascript"
// Output: "Hello World From Javascript"
function toTitleCase(str) {
return str.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');
}

// 26. Find Common Elements in Arrays
// Input: [1, 2, 3], [2, 3, 4]
// Output: [2, 3]
function findCommon(arr1, arr2) {
return arr1.filter(item => arr2.includes(item));
}

// 27. Sum of Digits
// Input: 12345
// Output: 15
function sumDigits(num) {
return String(num).split('').reduce((sum, digit) => sum + Number(digit), 0);
}

// 28. Remove Falsy Values from Array
// Input: [0, 1, false, 2, '', 3, null]
// Output: [1, 2, 3]
function removeFalsy(arr) {
return arr.filter(Boolean);
}

// 29. Find GCD of Two Numbers
// Input: 48, 18
// Output: 6
function gcd(a, b) {
return b === 0 ? a : gcd(b, a % b);
}

// 30. Chunk Array
// Input: [1, 2, 3, 4, 5], 2
// Output: [[1, 2], [3, 4], [5]]
function chunkArray(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}

// 31. Find All Indexes of Element
// Input: [1, 2, 3, 2, 5], 2
// Output: [1, 3]
function findAllIndexes(arr, element) {
return arr.reduce((indexes, val, i) => {
if (val === element) indexes.push(i);
return indexes;
}, []);
}

// 32. Rotate Array
// Input: [1, 2, 3, 4, 5], 2
// Output: [4, 5, 1, 2, 3]
function rotateArray(arr, k) {
k = k % arr.length;
return [...arr.slice(-k), ...arr.slice(0, -k)];
}

// 33. Check if String Contains Substring
// Input: "hello world", "world"
// Output: true
function containsSubstring(str, substr) {
return str.includes(substr);
}

// 34. Convert Celsius to Fahrenheit
// Input: 0
// Output: 32
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}

// 35. Find Average of Array
// Input: [1, 2, 3, 4, 5]
// Output: 3
function average(arr) {
return arr.reduce((sum, num) => sum + num, 0) / arr.length;
}

// 36. Swap Two Variables
// Input: a=5, b=10
// Output: a=10, b=5
function swap(a, b) {
return [b, a];
}

// 37. Count Words in String
// Input: "Hello world from JavaScript"
// Output: 4
function countWords(str) {
return str.trim().split(/\s+/).length;
}

// 38. Truncate String
// Input: "Hello World", 5
// Output: "Hello..."
function truncate(str, maxLength) {
return str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
}

// 39. Find Smallest Number in Array
// Input: [3, 7, 2, 9, 1]
// Output: 1
function findSmallest(arr) {
return Math.min(...arr);
}

// 40. Check if Leap Year
// Input: 2024
// Output: true
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

// 41. Reverse Each Word in String
// Input: "Hello World"
// Output: "olleH dlroW"
function reverseEachWord(str) {
return str.split(' ').map(word => word.split('').reverse().join('')).join(' ');
}

// 42. Find Unique Characters in String
// Input: "hello"
// Output: ["h", "e", "l", "o"]
function uniqueChars(str) {
return [...new Set(str)];
}

// 43. Binary to Decimal
// Input: "1010"
// Output: 10
function binaryToDecimal(binary) {
return parseInt(binary, 2);
}

// 44. Decimal to Binary
// Input: 10
// Output: "1010"
function decimalToBinary(decimal) {
return decimal.toString(2);
}

// 45. Shuffle Array
// Input: [1, 2, 3, 4, 5]
// Output: 3, 1, 5, 2, 4
function shuffleArray(arr) {
return arr.sort(() => Math.random() - 0.5);
}

// 46. Find Most Frequent Element
// Input: [1, 2, 2, 3, 3, 3, 4]
// Output: 3
function mostFrequent(arr) {
const freq = {};
let max = 0, result;
arr.forEach(item => {
freq[item] = (freq[item] || 0) + 1;
if (freq[item] > max) {
max = freq[item];
result = item;
}
});
return result;
}

// 47. Remove Specific Element from Array
// Input: [1, 2, 3, 4, 5], 3
// Output: [1, 2, 4, 5]
function removeElement(arr, element) {
return arr.filter(item => item !== element);
}

// 48. Check if All Elements are Unique
// Input: [1, 2, 3, 4, 5]
// Output: true
function allUnique(arr) {
return arr.length === new Set(arr).size;
}

// 49. Find Pairs with Given Sum
// Input: [1, 2, 3, 4, 5], 5
// Output: [[1, 4], [2, 3]]
function findPairs(arr, target) {
const pairs = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === target) {
pairs.push([arr[i], arr[j]]);
}
}
}
return pairs;
}

// 50. Calculate String Hash
// Input: "hello"
// Output: 99162322 (example hash value)
function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash = hash & hash;
}
return hash;
}

// ========================================
// Test Examples
// ========================================
console.log(reverseString("hello")); // "olleh"
console.log(isPalindrome("racecar")); // true
console.log(findLargest([3, 7, 2, 9, 1])); // 9
console.log(sumArray([1, 2, 3, 4, 5])); // 15
console.log(countVowels("hello world")); // 3

Top comments (0)