12 Common JavaScript Interview Coding  Questions (and Answers)

Photo by Luca Bravo on Unsplash

12 Common JavaScript Interview Coding Questions (and Answers)

In this article, we will discuss the most important interview coding questions.

1. Find the frequency of elements in array

using forEach()

function getFrequency(array) {
  var frequency = {};

  array.forEach(function(element) {
    if (frequency[element]) {
      frequency[element]++;
    } else {
      frequency[element] = 1;
    }
  });

  return frequency;
}

// Example 
var arr = [1, 2, 2, 3, 3, 3];
var result = getFrequency(arr);
console.log(result);

Output:

{
  1: 1,
  2: 2,
  3: 3
}

In this example, we use the forEach() method to iterate over the array. For each element in the array, we check if it exists as a key in the frequency object. If it does, we increment the count by 1. If it doesn't, we initialize it with a count of 1. Finally, we return the frequency object containing the count of each element in the array.

using reduce

function getFrequency(array) {
  return array.reduce(function(frequency, element) {
    frequency[element] = (frequency[element] || 0) + 1;
    return frequency;
  }, {});
}

// Example usage
var arr = [1, 2, 2, 3, 3, 3];
var result = getFrequency(arr);
console.log(result);

Output:

{
  1: 1,
  2: 2,
  3: 3
}

2. Find the pairs of array element for which sum is equal to given target value (Two Sum Problem)

  1. Brute Force Approach: The brute force approach involves nested loops to check all possible pairs of array elements. Here's an example:

     function findPairs(array, target) {
       var pairs = [];
    
       for (var i = 0; i < array.length; i++) {
         for (var j = i + 1; j < array.length; j++) {
           if (array[i] + array[j] === target) {
             pairs.push([array[i], array[j]]);
           }
         }
       }
    
       return pairs;
     }
    
     // Example usage
     var arr = [2, 4, 5, 7, 9];
     var target = 11;
     var result = findPairs(arr, target);
     console.log(result);
    

    Output:

     [[4, 7], [5, 6]]
    

    In this example, we iterate through the array using two nested loops. For each pair of elements, we check if their sum is equal to the target value. If it is, we add the pair to the pairs array.

  2. Using a Hash Map: Another efficient approach is to use a hash map to store the complement of each element (target minus the current element) while iterating through the array. Here's an example:

     function findPairs(array, target) {
       var pairs = [];
       var complements = {};
    
       for (var i = 0; i < array.length; i++) {
         var complement = target - array[i];
    
         if (complements[complement] !== undefined) {
           pairs.push([array[i], complement]);
         }
    
         complements[array[i]] = true;
       }
    
       return pairs;
     }
    
     // Example usage
     var arr = [2, 4, 5, 7, 9];
     var target = 11;
     var result = findPairs(arr, target);
     console.log(result);
    

    Output:

     [[4, 7], [5, 6]]
    

    In this example, we iterate through the array and calculate the complement of each element with respect to the target. If the complement exists in the complements hash map, we add the pair to the pairs array. Otherwise, we add the current element to the complements hash map.

3. Find the nth largest element

sorted array

function findNthLargestElement(array, n) {
  // Calculate the index of the nth largest element
  var index = array.length - n;

  // Return the element at the calculated index
  return array[index];
}

// Example usage
var arr = [1, 3, 5, 7, 9];
var n = 2;
var result = findNthLargestElement(arr, n);
console.log(result);

Output:

7

In this example, The array is already sorted in ascending order. We calculate the index of the nth largest element by subtracting n from the length of the array. Since array indices are zero-based, subtracting n from the length gives us the correct index. Finally, we return the element at the calculated index.

Unsorted array

var arr = [9, 2, 5, 1,10, 9];
var n = 2;

function findNthLargestElement(array, n) {
array.sort((a,b)=> a-b)
  // Calculate the index of the nth largest element
  var index = array.length - n;

  // Return the element at the calculated index
  return array[index];
}

// Example usage
var result = findNthLargestElement(arr, n);
console.log(result);

Output:

9

4. Remove duplicates from an array and return unique values

function removeDuplicates(array) {
  return array.filter((value, index) => array.indexOf(value) === index);
}

// Example usage
var arr = [1, 2, 2, 3, 4, 4, 5];
var uniqueValues = removeDuplicates(arr);
console.log(uniqueValues);

Output:

[1, 2, 3, 4, 5]

In this approach, we use the filter() method on the array and create a new array that only includes elements for which the index of the first occurrence matches the current index. This ensures that only the unique values are retained in the resulting array.

using the reduce()

function removeDuplicates(array) {
  return array.reduce(function (uniqueArray, currentValue) {
    if (!uniqueArray.includes(currentValue)) {
      uniqueArray.push(currentValue);
    }
    return uniqueArray;
  }, []);
}

// Example usage
var arr = [1, 2, 2, 3, 4, 4, 5];
var uniqueValues = removeDuplicates(arr);
console.log(uniqueValues);

Output:

[1, 2, 3, 4, 5]

In this approach, we use the reduce() method to iterate over the array and build a new array (uniqueArray) that contains only the unique values. For each element (currentValue) in the array, we check if it is already present in uniqueArray using the includes() method. If it is not present, we push it into uniqueArray. The reduce() method starts with an empty array ([]) as the initial value of uniqueArray and returns the final array of unique values.

5. Print all duplicate elements of an array

function printDuplicates(array) {
  var duplicates = array.filter(function (value, index) {
    return array.indexOf(value) !== index;
  });

  console.log(duplicates);
}

// Example usage
var arr = [1, 2, 2, 3, 4, 4, 5];
printDuplicates(arr);

Output:

[2, 2, 4, 4]

In this approach, we use the filter() method on the array to create a new array (duplicates) that includes elements for which the index of the first occurrence is not equal to the current index. This filters out all the elements that are not duplicates and leaves only the duplicate elements in the resulting array. Finally, we print the duplicates array.

6.Collect books from array of objects and return collection of books as an array

let users = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

let result = users.reduce((acc, curr)=> {
  acc.push(...curr.books);
  return acc;
}, []);

console.log(result);

Output:

 ["Bible", "Harry Potter", "War and peace", "Romeo and Juliet", "The Lord of the Rings", "The Shining"]

7.Reverse a string

Using split(), reverse(), and join():

function reverseString(str) {
  return str.split('').reverse().join('');
}

// Example usage
var string = 'Hello, World!';
var reversedString = reverseString(string);
console.log(reversedString);

Output:

!dlroW ,olleH

In this approach, we split the string into an array of characters using the split('') method. Then, we reverse the order of the array elements using the reverse() method. Finally, we join the array elements back into a string using the join('') method, resulting in the reversed string.

Using a for loop:

function reverseString(str) {
  var reversed = '';
  for (var i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

// Example usage
var string = 'Hello, World!';
var reversedString = reverseString(string);
console.log(reversedString);

Output:

!dlroW ,olleH

In this approach, we initialize an empty string reversed. We iterate over the characters of the input string from the last character to the first character using a for loop. Inside the loop, we append each character to the reversed string. Finally, we return the reversed string.

let users = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

let result = users.reduce((acc, curr)=> {
  acc.push(...curr.books);
  return acc;
}, []);

console.log(result);

Output:

 ["Bible", "Harry Potter", "War and peace", "Romeo and Juliet", "The Lord of the Rings", "The Shining"]

8.Find the Largest Number

function findLargestNumber(numbers) {
  if (numbers.length === 0) {
    return null; // Return null for an empty array
  }

  var largest = numbers[0]; // Assume the first number is the largest

  for (var i = 1; i < numbers.length; i++) {
    if (numbers[i] > largest) {
      largest = numbers[i]; // Update the largest number
    }
  }

  return largest;
}

// Example usage
var numbers = [10, 5, 8, 3, 12, 6];
var largestNumber = findLargestNumber(numbers);
console.log(largestNumber);

Output:

12

In this function, we first handle the case when the input array is empty by returning null. Then, we initialize a variable largest with the value of the first element in the array (numbers[0]). We iterate over the array starting from the second element (numbers[1]) and compare each number with the current largest value. If a number is larger than the current largest, we update the value of largest. After iterating through all the numbers in the array, we return the final value of largest.

Using reduce()

function findLargestNumber(numbers) {
 let res= numbers.reduce((acc,curr)=>{
return acc > curr ? acc : curr;
  })
  return res;
}

// Example usage
var numbers = [10, 5, 8, 3, 12, 6];
var largestNumber = findLargestNumber(numbers);
console.log(largestNumber);

Output:

12

8.Find the smallest Number

function findSmallestNumber(numbers) {
  if (numbers.length === 0) {
    return null; // Return null for an empty array
  }

  var smallest = numbers[0]; // Assume the first number is the smallest

  for (var i = 1; i < numbers.length; i++) {
    if (numbers[i] < smallest) {
      smallest = numbers[i]; // Update the smallest number
    }
  }

  return smallest;
}

// Example usage
var numbers = [10, 5, 8, 3, 12, 6];
var smallestNumber = findSmallestNumber(numbers);
console.log(smallestNumber);

Output:

3

Using reduce()

function findSmallestNumber(numbers) {
 let res= numbers.reduce((acc,curr)=>{
return acc < curr ? acc : curr;
  })
  return res;
}

// Example usage
var numbers = [10, 5, 8, 3, 12, 6];
var smallestNumber = findSmallestNumber(numbers);
console.log(smallestNumber );

Output:

3

9.Check for Palindrome

function isPalindrome(str) {
  let res = str.split("").reverse().join("");
  if (res === str) {
   return true;
  } else {
return false;
  }
}

var string = 'level';

Output:

true

10.Count Occurrences

function countOccurrences(arr, target) {
  var count = 0;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      count++;
    }
  }

  return count;
}

// Example usage
var array = [1, 2, 3, 4, 2, 2, 5, 2];
var targetElement = 2;
var occurrences = countOccurrences(array, targetElement);
console.log(occurrences);

Output:

4

11.Validate Parentheses

const isValid = (str) => {
  const stack = [];

  for (let i = 0; i < str.length; i += 1) {
    const top = stack[stack.length - 1];
    if (str[i] === '(' || str[i] === '{' || str[i] === '[') {
      stack.push(str[i]);
    } else if (str[i] === ')' && top === '(' && stack.length !== 0) {
      stack.pop();
    } else if (str[i] === ']' && top === '[' && stack.length !== 0) {
      stack.pop();
    } else if (str[i] === '}' && top === '{' && stack.length !== 0) {
      stack.pop();
    } else {
      return false;
    }
  }

  return stack.length === 0;
};

var string1 = '({})[]';
var string2 = '({[}])';
console.log(isValid(string1));
console.log(isValid(string2));

Output:

true
false

12.Find Longest Word

function findLongestWord(sentence) {
  // Remove any leading or trailing whitespace
  sentence = sentence.trim();

  // Split the sentence into an array of words
  var words = sentence.split(' ');

  // Sort the words array by length in descending order
  var sortedWords = words.sort(function(a, b) {
    return b.length - a.length;
  });

  // Return the first (longest) word in the sorted array
  return sortedWords[0];
}

// Example usage
var sentence = 'The quick brown fox jumps over the lazy dog';
var longestWord = findLongestWord(sentence);
console.log(longestWord);

Output:

jumps

In this approach, we follow these steps:

  1. Remove any leading or trailing whitespace from the input sentence using the trim() method.

  2. Split the sentence into an array of words using the split(' ') method, assuming words are separated by spaces.

  3. Sort the words array in descending order of length using the sort() method with a comparison function. This sorts the words from longest to shortest.

  4. Return the first (longest) word in the sorted array, which can be accessed using sortedWords[0].