50 Essential JavaScript Coding Problems with Solutions: Master Interview Questions and Coding Challenges | Dev Write


Are you preparing for a JavaScript interview or looking to sharpen your coding skills? This comprehensive guide features 50 essential JavaScript coding problems, complete with solutions, to help you master key concepts and tackle common interview questions. From array manipulations and string operations to algorithm challenges, these problems cover a wide range of topics that are crucial for any JavaScript developer. Dive in to test your skills, enhance your problem-solving abilities, and boost your confidence for your next coding interview!


  • Reverse a String

    • Problem: Reverse the given string.
    • Solution:
      function reverseString(str) { return str.split('').reverse().join(''); } // Example usage: // const str = "hello"; // console.log(reverseString(str)); // Output: "olleh"(code-box)
  • Find the Largest Number in an Array

    • Problem: Return the largest number in the array.
    • Solution:
      function findMax(arr) { return Math.max(...arr); } // Example usage: // const arr = [1, 5, 3, 9, 2]; // console.log(findMax(arr)); // Output: 9(code-box)
  • Check for Palindrome

    • Problem: Check if a given string is a palindrome.
    • Solution:
      function isPalindrome(str) { const cleaned = str.replace(/\W|_/g, '').toLowerCase(); return cleaned === cleaned.split('').reverse().join(''); } // Example usage: // const str = "A man, a plan, a canal, Panama"; // console.log(isPalindrome(str)); // Output: true(code-box)
  • Sum of All Numbers in an Array

    • Problem: Return the sum of all numbers in the array.
    • Solution:
      function sumArray(arr) { return arr.reduce((acc, num) => acc + num, 0); } // Example usage: // const arr = [1, 2, 3, 4]; // console.log(sumArray(arr)); // Output: 10(code-box)
  • Remove Duplicates from Array

    • Problem: Remove duplicates from an array.
    • Solution:
      function removeDuplicates(arr) { return [...new Set(arr)]; } // Example usage: // const arr = [1, 2, 2, 3, 4, 4]; // console.log(removeDuplicates(arr)); // Output: [1, 2, 3, 4](code-box)
  • Flatten Nested Arrays

    • Problem: Flatten a nested array.
    • Solution:
      function flattenArray(arr) { return arr.flat(Infinity); } // Example usage: // const arr = [1, [2, [3, [4]]]]; // console.log(flattenArray(arr)); // Output: [1, 2, 3, 4](code-box)
  • Find the Factorial of a Number

    • Problem: Compute the factorial of a given number.
    • Solution:
      function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); } // Example usage: // console.log(factorial(5)); // Output: 120(code-box)
  • Check if Array is Sorted

    • Problem: Check if the given array is sorted in ascending order.
    • Solution:
      function isSorted(arr) { for (let i = 1; i < arr.length; i++) { if (arr[i] < arr[i - 1]) return false; } return true; } // Example usage: // const arr = [1, 2, 3, 4]; // console.log(isSorted(arr)); // Output: true(code-box)
  • Count Vowels in a String

    • Problem: Count the number of vowels in the string.
    • Solution:
      function countVowels(str) { return (str.match(/[aeiou]/gi) || []).length; } // Example usage: // const str = "hello"; // console.log(countVowels(str)); // Output: 2(code-box)
  • Find the First Non-Repeated Character

    • Problem: Find the first non-repeated character in the string.
    • Solution:
      function firstNonRepeatedChar(str) { for (let i = 0; i < str.length; i++) { if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) return str[i]; } return null; } // Example usage: // const str = "swiss"; // console.log(firstNonRepeatedChar(str)); // Output: "w"(code-box)
  • Find Missing Number in Array

    • Problem: Find the missing number in a given array of integers from 1 to n.
    • Solution:
      function findMissingNumber(arr) { const n = arr.length + 1; const totalSum = (n * (n + 1)) / 2; const arrSum = arr.reduce((acc, num) => acc + num, 0); return totalSum - arrSum; } // Example usage: // const arr = [1, 2, 4, 5, 6]; // console.log(findMissingNumber(arr)); // Output: 3(code-box)
  • Find Common Elements in Two Arrays

    • Problem: Find common elements in two arrays.
    • Solution:
      function findCommonElements(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); } // Example usage: // const arr1 = [1, 2, 3]; // const arr2 = [2, 3, 4]; // console.log(findCommonElements(arr1, arr2)); // Output: [2, 3](code-box)
  • Find the Longest Word in a String

    • Problem: Find the longest word in a string.
    • Solution:
      function longestWord(str) { return str.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest, ''); } // Example usage: // const str = "The quick brown fox"; // console.log(longestWord(str)); // Output: "quick"(code-box)
  • Sort Array of Objects by Property

    • Problem: Sort an array of objects by a specific property.
    • Solution:
      function sortByProperty(arr, prop) { return arr.sort((a, b) => (a[prop] > b[prop]) ? 1 : -1); } // Example usage: // const arr = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 20 }]; // console.log(sortByProperty(arr, 'age')); // Output: [{ name: 'Bob', age: 20 }, { name: 'Alice', age: 25 }](code-box)
  • Find the Intersection of Two Arrays

    • Problem: Find the intersection of two arrays.
    • Solution:
      function arrayIntersection(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); } // Example usage: // const arr1 = [1, 2, 3, 4]; // const arr2 = [3, 4, 5, 6]; // console.log(arrayIntersection(arr1, arr2)); // Output: [3, 4](code-box)
  • Check if a Number is Prime

    • Problem: Check if a number is a prime number.
    • Solution:
      function isPrime(n) { if (n <= 1) return false; for (let i = 2; i <= Math.sqrt(n); i++) { if (n % i === 0) return false; } return true; } // Example usage: // console.log(isPrime(7)); // Output: true(code-box)
  • Find the Second Largest Number in an Array

    • Problem: Find the second largest number in an array.
    • Solution:
      function secondLargest(arr) { const uniqueArr = [...new Set(arr)]; if (uniqueArr.length < 2) return null; uniqueArr.sort((a, b) => b - a); return uniqueArr[1]; } // Example usage: // const arr = [10, 5, 20, 20, 15]; // console.log(secondLargest(arr)); // Output: 15(code-box)
  • Find the Missing Number in a Sequence

    • Problem: Given a sequence of numbers with one number missing, find the missing number.
    • Solution:
      function findMissingNumber(sequence) { const n = sequence.length + 1; const totalSum = (n * (n + 1)) / 2; const sequenceSum = sequence.reduce((acc, num) => acc + num, 0); return totalSum - sequenceSum; } // Example usage: // const sequence = [1, 2, 4, 5]; // console.log(findMissingNumber(sequence)); // Output: 3(code-box)
  • Check if Two Strings are Anagrams

    • Problem: Check if two strings are anagrams of each other.
    • Solution:
      function areAnagrams(str1, str2) { const sortStr = str => str.split('').sort().join(''); return sortStr(str1) === sortStr(str2); } // Example usage: // const str1 = "listen"; // const str2 = "silent"; // console.log(areAnagrams(str1, str2)); // Output: true(code-box)
  • Rotate Array to the Right

    • Problem: Rotate an array to the right by k steps.
    • Solution:
      function rotateArray(arr, k) { k = k % arr.length; return [...arr.slice(-k), ...arr.slice(0, -k)]; } // Example usage: // const arr = [1, 2, 3, 4, 5]; // console.log(rotateArray(arr, 2)); // Output: [4, 5, 1, 2, 3](code-box)
  • Find the Missing Letter in a String

    • Problem: Find the missing letter in a given range of letters.
    • Solution:
      function findMissingLetter(str) { const start = str.charCodeAt(0); for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) !== start + i) { return String.fromCharCode(start + i); } } return null; } // Example usage: // const str = "abdeg"; // console.log(findMissingLetter(str)); // Output: "c"(code-box)
  • Count Occurrences of a Character in a String

    • Problem: Count how many times a character appears in a string.
    • Solution:
      function countOccurrences(str, char) { return (str.match(new RegExp(char, 'g')) || []).length; } // Example usage: // const str = "hello world"; // console.log(countOccurrences(str, 'o')); // Output: 2(code-box)
  • Check if a String Contains Only Unique Characters

    • Problem: Check if a string contains only unique characters.
    • Solution:
      function hasUniqueChars(str) { return new Set(str).size === str.length; } // Example usage: // const str = "abcdef"; // console.log(hasUniqueChars(str)); // Output: true(code-box)
  • Generate Fibonacci Sequence

    • Problem: Generate the first n numbers in the Fibonacci sequence.
    • Solution:
      function fibonacci(n) { const sequence = [0, 1]; while (sequence.length < n) { const [a, b] = [sequence[sequence.length - 2], sequence[sequence.length - 1]]; sequence.push(a + b); } return sequence.slice(0, n); } // Example usage: // console.log(fibonacci(5)); // Output: [0, 1, 1, 2, 3](code-box)
  • Find All Prime Numbers up to a Given Number

    • Problem: Find all prime numbers up to a given number.
    • Solution:
      function getPrimes(n) { const primes = []; for (let i = 2; i <= n; i++) { if (isPrime(i)) primes.push(i); } return primes; } 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; } // Example usage: // console.log(getPrimes(10)); // Output: [2, 3, 5, 7](code-box)
  • Convert a String to Title Case

    • Problem: Convert a string to title case (capitalize the first letter of each word).
    • Solution:
      function toTitleCase(str) { return str.split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(' '); } // Example usage: // const str = "hello world"; // console.log(toTitleCase(str)); // Output: "Hello World"(code-box)
  • Find the Intersection of Three Arrays

    • Problem: Find the intersection of three arrays.
    • Solution:
      function arrayIntersectionThree(arr1, arr2, arr3) { return arr1.filter(value => arr2.includes(value) && arr3.includes(value)); } // Example usage: // const arr1 = [1, 2, 3]; // const arr2 = [2, 3, 4]; // const arr3 = [3, 4, 5]; // console.log(arrayIntersectionThree(arr1, arr2, arr3)); // Output: [3](code-box)
  • Find the Longest Substring Without Repeating Characters

    • Problem: Find the longest substring without repeating characters.
    • Solution:
      function longestUniqueSubstring(str) { let start = 0; let maxLength = 0; let usedChars = new Map(); for (let end = 0; end < str.length; end++) { if (usedChars.has(str[end])) { start = Math.max(usedChars.get(str[end]) + 1, start); } usedChars.set(str[end], end); maxLength = Math.max(maxLength, end - start + 1); } return maxLength; } // Example usage: // console.log(longestUniqueSubstring("abcabcbb")); // Output: 3(code-box)
  • Find All Unique Pairs in an Array That Sum to a Target Value

    • Problem: Find all unique pairs in an array that sum to a target value.
    • Solution:
      function findPairs(arr, target) { const pairs = []; const seen = new Set(); arr.forEach(num => { const complement = target - num; if (seen.has(complement)) { pairs.push([complement, num]); } seen.add(num); }); return pairs; } // Example usage: // const arr = [1, 2, 3, 4, 5]; // const target = 6; // console.log(findPairs(arr, target)); // Output: [[1, 5], [2, 4]](code-box)
  • Merge Two Sorted Arrays

    • Problem: Merge two sorted arrays into one sorted array.
    • Solution:
      function mergeSortedArrays(arr1, arr2) { const result = []; let i = 0, j = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { result.push(arr1[i++]); } else { result.push(arr2[j++]); } } return result.concat(arr1.slice(i)).concat(arr2.slice(j)); } // Example usage: // const arr1 = [1, 3, 5]; // const arr2 = [2, 4, 6]; // console.log(mergeSortedArrays(arr1, arr2)); // Output: [1, 2, 3, 4, 5, 6](code-box)
  • Implement a Simple Calculator

    • Problem: Implement a simple calculator that supports addition, subtraction, multiplication, and division.
    • Solution:
      function calculator(a, b, operation) { switch (operation) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: throw new Error('Invalid operation'); } } // Example usage: // console.log(calculator(5, 3, '+')); // Output: 8(code-box)
  • Check if a String Contains All Unique Characters (Case-Insensitive)

    • Problem: Check if a string contains all unique characters, case-insensitive.
    • Solution:
      function hasUniqueCharsCaseInsensitive(str) { str = str.toLowerCase(); return new Set(str).size === str.length; } // Example usage: // const str = "aBcDeF"; // console.log(hasUniqueCharsCaseInsensitive(str)); // Output: true(code-box)
  • Calculate the Power of a Number

    • Problem: Calculate the power of a number using a base and an exponent.
    • Solution:
      function power(base, exponent) { return base ** exponent; } // Example usage: // console.log(power(2, 3)); // Output: 8(code-box)
  • Find the Mode of an Array

    • Problem: Find the mode (most frequently occurring number) in an array.
    • Solution:
      function findMode(arr) { const frequency = {}; let maxFreq = 0; let mode = []; arr.forEach(num => { frequency[num] = (frequency[num] || 0) + 1; if (frequency[num] > maxFreq) { maxFreq = frequency[num]; mode = [num]; } else if (frequency[num] === maxFreq) { mode.push(num); } }); return mode; } // Example usage: // const arr = [1, 2, 2, 3, 3, 3]; // console.log(findMode(arr)); // Output: [3](code-box)
  • Generate a Random Integer between Two Values

    • Problem: Generate a random integer between two given values, inclusive.
    • Solution:
      function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Example usage: // console.log(getRandomInt(1, 10)); // Output: Random number between 1 and 10(code-box)
  • Find the Greatest Common Divisor (GCD) of Two Numbers

    • Problem: Find the GCD of two numbers using the Euclidean algorithm.
    • Solution:
      function gcd(a, b) { while (b) { [a, b] = [b, a % b]; } return a; } // Example usage: // console.log(gcd(56, 98)); // Output: 14(code-box)
  • Convert a Number to Binary

    • Problem: Convert a number to its binary representation.
    • Solution:
      function toBinary(num) { return num.toString(2); } // Example usage: // console.log(toBinary(10)); // Output: "1010"(code-box)
  • Find the Sum of Digits in a Number

    • Problem: Find the sum of the digits of a number.
    • Solution:
      function sumOfDigits(num) { return num.toString().split('').reduce((sum, digit) => sum + Number(digit), 0); } // Example usage: // console.log(sumOfDigits(123)); // Output: 6(code-box)
  • Convert a Binary String to a Decimal Number

    • Problem: Convert a binary string to its decimal number representation.
    • Solution:
      function binaryToDecimal(binaryStr) { return parseInt(binaryStr, 2); } // Example usage: // console.log(binaryToDecimal("1010")); // Output: 10(code-box)
  • Find the Number of Words in a String

    • Problem: Find the number of words in a string.
    • Solution:
      function countWords(str) { return str.split(/\s+/).filter(Boolean).length; } // Example usage: // const str = "Hello world, this is a test."; // console.log(countWords(str)); // Output: 6(code-box)
  • Find the Intersection of Multiple Arrays

    • Problem: Find the intersection of multiple arrays.
    • Solution:
      function intersectionOfArrays(...arrays) { return arrays.reduce((acc, arr) => acc.filter(value => arr.includes(value))); } // Example usage: // const arr1 = [1, 2, 3]; // const arr2 = [2, 3, 4]; // const arr3 = [3, 4, 5]; // console.log(intersectionOfArrays(arr1, arr2, arr3)); // Output: [3](code-box)
  • Find the Length of the Longest Word in a String

    • Problem: Find the length of the longest word in a string.
    • Solution:
      function lengthOfLongestWord(str) { return Math.max(...str.split(' ').map(word => word.length)); } // Example usage: // const str = "The quick brown fox"; // console.log(lengthOfLongestWord(str)); // Output: 5(code-box)
  • Check if a String is a Valid Email Address

    • Problem: Check if a string is a valid email address.
    • Solution:
      function isValidEmail(email) { const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return re.test(email); } // Example usage: // const email = "test@example.com"; // console.log(isValidEmail(email)); // Output: true(code-box)
  • Count the Number of Characters in a String

    • Problem: Count the number of characters in a string.
    • Solution:
      function countCharacters(str) { return str.length; } // Example usage: // const str = "hello"; // console.log(countCharacters(str)); // Output: 5(code-box)
  • Find the Most Frequent Character in a String

    • Problem: Find the most frequent character in a string.
    • Solution:
      function mostFrequentChar(str) { const frequency = {}; let maxChar = ''; let maxFreq = 0; for (const char of str) { frequency[char] = (frequency[char] || 0) + 1; if (frequency[char] > maxFreq) { maxFreq = frequency[char]; maxChar = char; } } return maxChar; } // Example usage: // const str = "hello"; // console.log(mostFrequentChar(str)); // Output: "l"(code-box)
  • Check if a String Contains Only Digits

    • Problem: Check if a string contains only digits.
    • Solution:
      function isDigitsOnly(str) { return /^\d+$/.test(str); } // Example usage: // const str = "12345"; // console.log(isDigitsOnly(str)); // Output: true(code-box)
  • Remove All Instances of a Given Character from a String

    • Problem: Remove all instances of a given character from a string.
    • Solution:
      function removeChar(str, char) { return str.split(char).join(''); } // Example usage: // const str = "hello world"; // console.log(removeChar(str, 'o')); // Output: "hell wrld"(code-box)
  • Find the Index of the First Occurrence of a Substring

    • Problem: Find the index of the first occurrence of a substring within a string.
    • Solution:
      function indexOfSubstring(str, substring) { return str.indexOf(substring); } // Example usage: // const str = "hello world"; // console.log(indexOfSubstring(str, 'world')); // Output: 6(code-box)
  • Replace All Instances of a Substring in a String

    • Problem: Replace all instances of a substring in a string with a new substring.
    • Solution:
      function replaceSubstring(str, oldSubstring, newSubstring) { return str.split(oldSubstring).join(newSubstring); } // Example usage: // const str = "hello world"; // console.log(replaceSubstring(str, 'world', 'everyone')); // Output: "hello everyone"(code-box)
  • Check if a Number is a Power of Two

    • Problem: Check if a number is a power of two.
    • Solution:
      function isPowerOfTwo(n) { return (n > 0) && (n & (n - 1)) === 0; } // Example usage: // console.log(isPowerOfTwo(16)); // Output: true (code-box) 

       

Conclusion 

Mastering JavaScript coding problems is a critical step in preparing for technical interviews and enhancing your problem-solving skills. By working through these 50 essential challenges, you can build a strong foundation in key JavaScript concepts and algorithms. Whether you're aiming to improve your coding proficiency or seeking to impress potential employers, practicing these problems will provide valuable insights and help you become a more confident and capable developer. Keep these solutions handy, revisit them regularly, and continue to push the boundaries of your knowledge to stay ahead in the ever-evolving field of web development. Happy coding!

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!