Powered by Thakur Technologies

    JavaScript interview questions & answers with code

    Top JavaScript Interview Questions and Expert Answers with Code Examples


    1. Flatten a Nested Object

    Question: Write a function to flatten a nested JavaScript object.

    Code:

    function flattenObject(obj, prefix = '', res = {}) {

      for (let key in obj) {

        const newKey = prefix ? `${prefix}.${key}` : key;

        if (typeof obj[key] === 'object' && obj[key] !== null) {

          flattenObject(obj[key], newKey, res);

        } else {

          res[newKey] = obj[key];

        }

      }

      return res;

    }

    console.log(flattenObject({ a: { b: { c: 1 } }, d: 2 }));

    // Output: { 'a.b.c': 1, d: 2 }


    2. Find Duplicates in an Array

    Question: Write a function to find duplicate values in an array.

    Code:

    function findDuplicates(arr) {

      const counts = {};

      return arr.filter(item => counts[item] ? true : (counts[item] = 1, false));

    }

    console.log(findDuplicates([1, 2, 2, 3, 4, 4, 5]));

    // Output: [2, 4]


    3. Implement debounce

    Question: Write a debounce function that limits the rate a function is called.

    Code:

    function debounce(func, delay) {

      let timer;

      return function (...args) {

        clearTimeout(timer);

        timer = setTimeout(() => func.apply(this, args), delay);

      };

    }

    const log = debounce(() => console.log('Logged after 1s'), 1000);

    log();


    4. Reverse a String Recursively

    Question: Write a recursive function to reverse a string.

    Code:

    function reverseString(str) {

      if (str === "") return "";

      return reverseString(str.slice(1)) + str[0];

    }

    console.log(reverseString("hello"));

    // Output: "olleh"


    5. Check for Palindrome

    Question: Write a function to check if a string is a palindrome.

    Code:

    function isPalindrome(str) {

      const cleaned = str.toLowerCase().replace(/[^a-z]/g, '');

      return cleaned === cleaned.split('').reverse().join('');

    }

    console.log(isPalindrome("A man, a plan, a canal, Panama"));

    // Output: true


    6. Generate Fibonacci Sequence

    Question: Write a function to generate Fibonacci sequence up to n terms.

    Code:

    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);

    }

    console.log(fibonacci(7));

    // Output: [0, 1, 1, 2, 3, 5, 8]


    7. Find Intersection of Two Arrays

    Question: Write a function to find the intersection of two arrays.

    Code:

    function arrayIntersection(arr1, arr2) {

      return arr1.filter(value => arr2.includes(value));

    }

    console.log(arrayIntersection([1, 2, 3], [2, 3, 4]));

    // Output: [2, 3]


    8. Sum of Array with Reduce

    Question: Write a function to sum all numbers in an array using reduce.

    Code:

    function sumArray(arr) {

      return arr.reduce((acc, num) => acc + num, 0);

    }

    console.log(sumArray([1, 2, 3, 4]));

    // Output: 10


    9. Filter Even Numbers

    Question: Write a function to filter even numbers from an array.

    Code:

    function filterEven(arr) {

      return arr.filter(num => num % 2 === 0);

    }

    console.log(filterEven([1, 2, 3, 4, 5, 6]));

    // Output: [2, 4, 6]


    10. Count Occurrences in Array

    Question: Write a function to count occurrences of each element in an array.

    Code:

    function countOccurrences(arr) {

      return arr.reduce((acc, num) => {

        acc[num] = (acc[num] || 0) + 1;

        return acc;

      }, {});

    }

    console.log(countOccurrences([1, 2, 2, 3, 3, 3]));

    // Output: {1: 1, 2: 2, 3: 3}


    11. Flatten an Array

    Question: Write a function to flatten an array of arrays.

    Code:

    function flattenArray(arr) {

      return arr.flat(Infinity);

    }

    console.log(flattenArray([1, [2, [3, 4]], 5]));

    // Output: [1, 2, 3, 4, 5]


    12. Capitalize First Letter of Each Word

    Question: Write a function to capitalize the first letter of each word in a string.

    Code:

    function capitalizeWords(str) {

      return str.replace(/\b\w/g, char => char.toUpperCase());

    }

    console.log(capitalizeWords("hello world"));

    // Output: "Hello World"


    13. Convert Array of Objects to Single Object

    Question: Convert an array of objects to a single object with keys and values.

    Code:

    function arrayToObject(arr) {

      return arr.reduce((acc, item) => ({ ...acc, ...item }), {});

    }

    console.log(arrayToObject([{ a: 1 }, { b: 2 }, { c: 3 }]));

    // Output: { a: 1, b: 2, c: 3 }


    14. Get Unique Values in Array

    Question: Write a function to get unique values in an array.

    Code:

    function uniqueArray(arr) {

      return [...new Set(arr)];

    }

    console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5]));

    // Output: [1, 2, 3, 4, 5]


    15. Find Maximum Value in Array

    Question: Write a function to find the maximum value in an array.

    Code:

    function maxInArray(arr) {

      return Math.max(...arr);

    }

    console.log(maxInArray([1, 2, 3, 4, 5]));

    // Output: 5


    16. Sort an Array of Objects

    Question: Sort an array of objects by a specified key.

    Code:

    function sortByKey(arr, key) {

      return arr.sort((a, b) => (a[key] > b[key] ? 1 : -1));

    }

    console.log(sortByKey([{ age: 30 }, { age: 20 }], 'age'));

    // Output: [{ age: 20 }, { age: 30 }]

    17. Check Prime Number

    Question: Write a function to check if a number is prime.

    Code:

    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;

    }

    console.log(isPrime(11));

    // Output: true


    18. Binary Search Implementation

    Question: Implement binary search on a sorted array.

    Code:

    function binarySearch(arr, target) {

      let left = 0, right = arr.length - 1;

      while (left <= right) {

        const mid = Math.floor((left + right) / 2);

        if (arr[mid] === target) return mid;

        if (arr[mid] < target) left = mid + 1;

        else right = mid - 1;

      }

      return -1;

    }

    console.log(binarySearch([1, 2, 3, 4, 5], 3));

    // Output: 2


    19. Group By Property

    Question: Write a function to group objects by a specified property.

    Code:

    function groupBy(arr, key) {

      return arr.reduce((acc, obj) => {

        const keyValue = obj[key];

        acc[keyValue] = acc[keyValue] || [];

        acc[keyValue].push(obj);

        return acc;

      }, {});

    }

    console.log(groupBy([{ age: 20 }, { age: 30 }, { age: 20 }], 'age'));

    // Output: { 20: [{ age: 20 }, { age: 20 }], 30


    20. Implement a Function to Chunk an Array

    Question: Write a function chunkArray that splits an array into smaller arrays of a specified length. If the array cannot be split evenly, the final chunk should contain the remaining elements.

    Example:

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    console.log(chunkArray(arr, 3));

    // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


    console.log(chunkArray(arr, 4));

    // Output: [[1, 2, 3, 4], [5, 6, 7, 8], [9]]


    Solution:

    You can implement this using a loop to create slices of the array in chunks of the specified size.

    function chunkArray(arr, size) {

      const result = [];

      for (let i = 0; i < arr.length; i += size) {

        result.push(arr.slice(i, i + size));

      }

      return result;

    }


    // Testing the function

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    console.log(chunkArray(arr, 3));  // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    console.log(chunkArray(arr, 4));  // Output: [[1, 2, 3, 4], [5, 6, 7, 8], [9]]





    Responsive Ad Box


    FAQs

    Frequently Asked Questions (FAQs)

    AI-generated art is created using algorithms that analyze vast datasets of images, patterns, and styles to produce unique artworks. Tools like DALL-E and MidJourney generate art based on text prompts provided by users, using machine learning models to simulate creativity and design.
    There’s debate over the originality of AI-generated art, as AI models are trained on pre-existing works. While the output is unique, it often blends elements from past artworks, raising questions about authorship and originality.
    These tools make art creation accessible to a broader audience, allowing users with no formal training to generate professional-level digital art. They are also driving innovation in areas like digital sculptures, interactive art, and NFTs, pushing the boundaries of traditional art forms.
    Key ethical concerns include issues of copyright, as AI often learns from existing art, potentially copying elements without permission. There are also concerns about the displacement of human artists and the environmental impact of AI-driven NFT transactions.
    Yes, AI-generated art is increasingly being sold as NFTs (non-fungible tokens) on blockchain platforms, and some artists are also using AI to create physical art pieces such as sculptures or digital prints for sale in galleries. This commercialization is opening new revenue streams for artists and creators.



    Support Section with SVG

    Did you find this article valuable?

    Support Atharv Gyan by becoming a sponsor.





    Like

    Share


    # Tags

    Powered by Thakur Technologies