Javascript Questions
by Satyam Singh
Scroll down for Questions   ⬇️

JavaScript Coding Questions
By Satyam
  1. 1. Programming Question: Hash Tag Generator
    View Solution
    You are required to implement a function generateHash that generates a hash tag from a given input string. The hash tag should be constructed as follows:
    
    The input string should be converted to a hash tag format, where each word is capitalized and concatenated together without spaces.
    If the length of the input string is greater than 280 characters or if the input string is empty or contains only whitespace, the function should return false.
    Otherwise, the function should return the generated hash tag prefixed with #.
    
    const generateHash = (str) => {
      if (str.length > 280 || str.trim().length === 0) {
        return false;
      }
    
      str = str.split(" ");
      str = str.map((currElement) => currElement.replace(currElement[0], currElement[0].toUpperCase()));
      str = `#${str.join("")}`;
      return str;
    };
    
    console.log(generateHash("my name is Satyam Singh"));
  2. 2. Check if a given array of integers represents a valid mountain array.
    View Solution
    function isValidMountainArray(arr) {
        const n = arr.length;
        if (n < 3) return false;
    
        let i = 0;
    
        // Walk up
        while (i + 1 < n && arr[i] < arr[i + 1]) {
            i++;
        }
    
        // Peak can't be first or last
        if (i === 0 || i === n - 1) return false;
    
        // Walk down
        while (i + 1 < n && arr[i] > arr[i + 1]) {
            i++;
        }
    
        return i === n - 1;
    }
    
    // Example usage
    const arr1 = [2, 1];
    const arr2 = [3, 5, 5];
    const arr3 = [0, 3, 2, 1];
    
    console.log(isValidMountainArray(arr1)); // Output: false
    console.log(isValidMountainArray(arr2)); // Output: false
    console.log(isValidMountainArray(arr3)); // Output: true
  3. 3. Write a function called countChar that takes two parameters, a string and a character to count
    View Solution
     // Constraints: // - The function should be case-sensitive. 
     - The function should handle both lowercase and uppercase characters.//
     - The character parameter can be any printable ASCII character. 
    function countChar(str, char) {
      // Convert the input string and specified character to lowercase
      str = str.toLowerCase();
      char = char.toLowerCase();
      let count = 0;
    
      // Iterate through each character in the string
      for (let i = 0; i < str.length; i++) {
        // Check if the current character matches the specified character
        if (str.charAt(i) === char) {
          // Increment count if the characters match
          count++;
        }
      }
    
      // Return the total count of occurrences
      return count;
    }
    
    // Test the function with an example
    console.log(countChar("MissIssippi", "I"));
    // Output: 4
  4. 4. Determine the type of triangle based on the lengths of its sides
    View Solution
    Function: checkTriangleType
    Description: Determines the type of triangle based on the lengths of its sides.
    Parameters:
      - side1: Length of the first side of the triangle.
      - side2: Length of the second side of the triangle.
      - side3: Length of the third side of the triangle.
    Returns: A string indicating the type of triangle: "equilateral", "isosceles", or "scalene"
    
    const checkTriangleType = (a, b, c) => {
      if (a === b && b === c && a === c) {
        return "equilateral";
      }
      if (a === b || b === c || a === c) {
        return "isosceles";
      }
      return "scalene";
    }; 
    console.log(checkTriangleType(3, 3, 3)); // Output: equilateral 
    console.log(checkTriangleType(3, 4, 3)); // Output: isosceles
  5. 5. Write a function to sort an array of numbers in ascending order
    View Solution
    Requirements: \n- The function should take an array of numbers as input. \n- It should return a new array with the numbers sorted in ascending order.\n- The original array should remain unchanged.\n-  const sortAscending =(arr) => \n{return arr.sort((a, b) => a-b) \n console.log(sortAscending([5, 3, 10, 8])); \n// Output: [3, 5, 8, 10]
  6. 6. Write a function to determine whether a given string is a palindrome or not.
    View Solution
    Function: isPalindrome
    Description: Determines whether a given string is a palindrome.
    Parameters: 
    - str: The input string to be checked.
    Returns: Boolean true if the input string is a palindrome, otherwise false.
    
    const isPalindrome = (str) => {
      str = str.toLowerCase().replace(/\W/g, '');
      let reversedStr = str.split('').reverse().join('');
      return reversedStr === str;
    };
    
    // Test cases:
    console.log(isPalindrome('A man, a plan, a canal, Panama')); // Output: true
    console.log(isPalindrome('racecar')); // Output: true
    console.log(isPalindrome('hello')); // Output: false
    
    // Constraints:
    // - The input string may contain letters, digits, spaces, punctuation, and special characters.
    // - The function should be case-insensitive, treating 'Racecar' and 'racecar' as the same.
    // - Ignore spaces, punctuation, and special characters when determining if a string is a palindrome.
    // - The function should return true if the input string is a palindrome and false otherwise.
  7. 7. Write a function findMax that takes an array of numbers as input and returns the maximum number in the array.
    View Solution
    Function: findMax
    Description: Finds the maximum number in an array of numbers.
    Parameters: 
    - numbers: An array of numbers.
    Returns: The maximum number found in the array, or undefined if the input is not an array or empty.
    
    function findMax(numbers) {
        if (!Array.isArray(numbers) || numbers.length === 0) {
            return undefined; // Handle edge cases where input is not an array or empty
        }
    
        let max = numbers[0]; // Initialize max with the first element of the array
        for (let i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i]; // Update max if current element is greater
            }
        }
        return max;
    }
    
    // Example usage:
    console.log(findMax([1, 5, 3, 9, 21])); // Output: 21
    console.log(findMax([-10, -5, -3, -9, -2])); // Output: -2
    console.log(findMax([])); // Output: undefined
  8. 8. Write a function factorial that takes a non-negative integer num as input and returns its factorial.
    View Solution
    Function: factorial
    Description: Calculates the factorial of a non-negative integer.
    Parameters: 
    - num: A non-negative integer for which factorial is to be calculated.
    Returns: The factorial of num, which is the product of all positive integers less than or equal to num.
    
    const factorial = (num) => {
      let fact = 1;
      for (let i = 1; i <= num; i++) {
        fact = fact * i;
      }
      return fact;
    };
    
    console.log(factorial(5)); // Output: 120
    
    
    Function: factorial2
    Description: Calculates the factorial of a non-negative integer using recursion.
    Parameters: 
    - num: A non-negative integer for which factorial is to be calculated.
    Returns: The factorial of num, which is the product of all positive integers less than or equal to num.
    
    function factorial2(num) {
      // Base case: if num is 0, return 1
      if (num === 0) {
        return 1;
      }
      // Recursive case: multiply num by the factorial of num - 1
      else {
        return num * factorial2(num - 1);
      }
    }
    
    console.log(factorial2(5)); // Output: 120
  9. 9. Write a function called calculateAverage that takes an array of numbers as input and returns the average of those numbers.
    View Solution
    Function: calculateAverage
    Description: Calculates the average of an array of numbers.
    Parameters: 
    - numbers: An array of numbers for which the average is to be calculated.
    Returns: The average of the numbers in the input array.
    
    const calculateAverage = (numbers) => {
        // Check if the input array is empty
        if (numbers.length === 0) {
            return 0; // If empty, return 0 to avoid division by zero
        }
        
        let sum = 0;
        // Loop through the array to calculate the sum of all numbers
        for (let i = 0; i < numbers.length; i++) {
            sum = sum +  numbers[i];
        }
        
        // Calculate the average by dividing the sum by the number of elements
        return sum / numbers.length;
    };
    
    // Example usage:
    console.log(calculateAverage([1, 2, 3, 4, 5])); // Output: 3
    console.log(calculateAverage([10, 20, 30])); // Output: 20
  10. 10. Write a function arraysAreEqual that takes two arrays arr1 and arr2 as input and returns true if the arrays are equal (i.e., contain the same elements in the same order), and false otherwise.
    View Solution
    Function: arraysAreEqual
    Description: Checks if two arrays are equal by comparing their elements in order.
    Parameters: 
    - arr1: The first array to compare.
    - arr2: The second array to compare.
    Returns: A boolean value indicating whether the arrays are equal.
    
    // Function definition
    function arraysAreEqual(arr1, arr2) {
        // Check if the arrays have the same length
        if (arr1.length !== arr2.length) {
            return false;
        }
    
        // Compare each element of the arrays
        for (let i = 0; i < arr1.length; i++) {
            // If any elements are not equal, return false
            if (arr1[i] !== arr2[i]) {
                return false;
            }
        }
    
        // If all elements are equal, return true
        return true;
    }
    
    // Example usage:
    console.log(arraysAreEqual([1, 2, 31], [1, 2, 31])); // Output: true
    console.log(arraysAreEqual([1, 2, 31], [1, 2, 41])); // Output: false
    console.log(arraysAreEqual([], [])); // Output: true
  11. 11. Write a function that takes a number as input and returns the sum of its digits.
    View Solution
    Function: sumOfDigits
    Description: Calculates the sum of the digits of a given number.
    Parameters: 
    - num: The input number whose digits are to be summed.
    Returns: The sum of the digits of the input number.
    
    const sumOfDigits = (num) => {
        let sum = 0;
        while (num != 0) {
            let digit = num % 10;
            sum = sum + digit;
            num = Math.floor(num / 10);
        }
        return sum;
    };
    
    // Example usage:
    console.log(sumOfDigits(1234)); // Output: 10
    console.log(sumOfDigits(4321)); // Output: 10
    console.log(sumOfDigits(123456)); // Output: 21
    
    // Constraints:
    // - The input number will always be a positive integer.
    // - The input number can have multiple digits.
    // - The output should be the sum of all the digits in the input number.
    
    // Homework:
    // This function calculates the sum of digits without converting the number to a string.
  12. 12. Write a function that takes an array of integers as input and removes any duplicate elements, returning a new array with only the unique elements.
    View Solution
    Function: removeDuplicates
    Description: Removes duplicate elements from an array of integers and returns a new array with only unique elements.
    
    1st Method to Remove Duplicates:
    
    const removeDuplicates = (arr) => {
        return [...new Set(arr)];
    };
    
    2nd Method to Remove Duplicates (In-Place):
    
    const removeDuplicatesInPlace = (arr) => {
        for (let i = 0; i < arr.length; i++) {
            for (let j = i + 1; j < arr.length;) {
                if (arr[i] === arr[j]) {
                    arr.splice(j, 1); // Remove the duplicate element j = which element and 1 = how many elements to remove
                } else {
                    j++; // Move to the next element
                }
            }
        }
        return arr;
    };
    
    // Example usage:
    console.log(removeDuplicates([1, 2, 3, 4])); // Output: [1, 2, 3, 4]
    console.log(removeDuplicates([])); // Output: []
    console.log(removeDuplicates([1, 2, 3, 2, 1, 4])); // Output: [1, 2, 3, 4]
    console.log(removeDuplicates([5, 6, 7, 7, 8, 8, 9])); // Output: [5, 6, 7, 8, 9]
    
    // Constraints:
    // - The input array may contain both positive and negative integers.
    // - The input array may be empty.
    // - The output array should retain the original order of elements.
  13. 13. Write a function that takes a string as input and returns the count of vowels in that string. Consider 'a', 'e', 'i', 'o', and 'u' as vowels (both lowercase and uppercase).
    View Solution
    Function: countVowels
    Description: Counts the number of vowels in a given string, considering both lowercase and uppercase vowels ('a', 'e', 'i', 'o', 'u').
    
    const countVowels = (str) => {
        let vowels = ["a", "e", "i", "o", "u"];
        let arr = str.split("");
        let count = 0;
        for (let char of arr) {
            if (vowels.includes(char.toLowerCase())) {
                count++;
            }
        }
        return count;
    };
    
    // Example usage:
    console.log(countVowels("Helloo world")); // Output: 4
    console.log(countVowels("ThE quIck brOwn fOx")); // Output: 5
    console.log(countVowels("Brrrp")); // Output: 0
    
    // Constraints:
    // - The input string may contain letters in both uppercase and lowercase.
    // - The output should be a non-negative integer representing the count of vowels in the input string.
  14. 14. Write a function called isPowerOfTwo that takes an integer num as input and returns true if num is a power of two, and false otherwise.
    View Solution
    Function: isPowerOfTwo
    Description: Determines whether a given integer is a power of two.
    
    const isPowerOfTwo = (num) => {
        for (let i = 1; i <= num; i++) {
            if (2 ** i === num) {
                return true;
            }
        }
        return false;
    };
    
    // Example usage:
    console.log(isPowerOfTwo(8)); // Output: true
    console.log(isPowerOfTwo(7)); // Output: false
    
    // Using bitwise operators:
    // const isPowerOfTwo = (num) => {
    //     return num > 0 && (num & (num - 1)) === 0;
    // };
    // console.log(isPowerOfTwo(8)); // Output: true
    // console.log(isPowerOfTwo(7)); // Output: false
    
    // Notes:
    // - The input num will be a positive integer.
    // - Zero (0) and negative integers are not considered powers of two.
    // - The function should return true if the given number is a power of 2, and false otherwise.
    
    // We can solve it using bitwise operators too, but it's your chance to do it and let me know in the comment section.
  15. 15. Write a function to calculate the sum of squares of all elements in an array. For example, given the array [1, 2, 3], the function should return 14 because 1*1 + 2*2 + 3*3 = 1 + 4 + 9 = 14.
    View Solution
    Function: sumOfSquares
    Description: Calculates the sum of squares of all elements in an array.
    
    function sumOfSquares(arr) {
      let sum = 0;
      for (let i = 0; i < arr.length; i++) {
        sum += arr[i] * arr[i];
      }
      return sum;
    }
    
    // Example usage:
    console.log(sumOfSquares([1, 2, 3])); // Output: 14
    
    // Constraints:
    // - The input array may contain both positive and negative integers.
    // - The input array may be empty, in which case the function should return 0.
    // - The function should handle large arrays efficiently.