JavaScript snippets for Coding Interview
In this article, we will cover some JavaScript snippets that are commonly used in coding interviews. These snippets will help you solve coding problems more efficiently and effectively.
Table of Contents
Arrays
Create & initialize an array
const arr = new Array(5).fill(0);
console.log(arr); // [0, 0, 0, 0, 0]
Create and initialize matrix
const rowsSize = 2;
const colsSize = 3;
let matrix = [...Array(rowsSize)].map(row => Array(colsSize).fill(0));
console.log(matrix); // [[0, 0, 0], [0, 0, 0]]
Get subarray from array
Use arr.slice(leftIdx, rightIdx+1)
approach
const arr = [1, 2, 3, 4, 5];
const subArr = arr.slice(1, 3);
console.log(subArr); // [2, 3]
Find max element in array
const arr = [1, 2, 3, 4, 5];
const max = Math.max(...arr);
console.log(max); // 5
Swap two numbers in array
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]
// Swap two numbers at index 0 and 1
[arr[0], arr[1]] = [arr[1], arr[0]]
console.log(arr) // [ 2, 1, 3, 4, 5 ]
reduce()
to calculate sum of array
reduce()
is a function that takes two arguments, an accumulator and a currentValue, and returns a single value. It can be used to calculate the sum of an array.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Strings
Reverse a string
To reverse a string, you can split the string into an array of characters, reverse the array, and then join the characters back into a string.
const str = 'hello';
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 'olleh'
Check if string is palindrome
const isPalindrome = (str) => {
return str === str.split('').reverse().join('');
}
console.log(isPalindrome('hello')); // false
console.log(isPalindrome('madam')); // true
Count occurrences of a character in a string
const str = 'hello';
const char = 'l';
const count = str.split('').filter(c => c === char).length;
console.log(count); // 2
Sort String
To sort a string, you can split the string into an array of characters, sort the array, and then join the characters back into a string.
const str = 'hello';
const sortedStr = str.split('').sort().join('');
console.log(sortedStr); // 'ehllo'
Objects
Merge two objects
To merge two objects, you can use the spread operator (...
) to create a new object with the properties of both objects.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 3, c: 4 }
Check if object has a property
You can use the in
operator to check if an object has a property.
const obj = { a: 1, b: 2 };
console.log('a' in obj); // true
console.log('c' in obj); // false
Get all keys of an object
You can use the Object.keys()
method to get an array of all keys of an object.
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj);
console.log(keys); // ['a', 'b', 'c']
Iterate through Object
You can use for...in
loop to iterate through the keys of an object.
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]);
}
Numbers
Generate random number in a range
const min = 1;
const max = 10;
const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomNum);
Convert Number to given base
const num = 10;
const base = 2;
const convertedNum = num.toString(base);
console.log(convertedNum); // '1010'
Map
Initialize Map
const map = new Map();
map.set('a', 1);
map.set('b', 2);
console.log(map); // Map { 'a' => 1, 'b' => 2 }
Iterate through Map
To iterate through a Map, you can use a for...of
loop.
const map = new Map();
map.set('a', 1);
map.set('b', 2);
for (const [key, value] of map) {
console.log(key, value);
}
Set
Initialize Set
const set = new Set();
set.add(1);
set.add(2);
console.log(set); // Set { 1, 2 }
Iterate through Set
To iterate through a Set, you can use a for...of
loop.
const set = new Set();
set.add(1);
set.add(2);
for (const value of set) {
console.log(value);
}
Adhoc
Check is given input a letter
To check if a given input is a letter you can use the following approach:
const isLetter = (value) => {
return /^[a-zA-Z]$/.test(value);
}
console.log(isLetter('a')); // true
console.log(isLetter('B')); // true
console.log(isLetter('AB')); // false, more than one character
console.log(isLetter('')); // false, empty string
console.log(isLetter('*')); // false, wrong character
In the following code:
/.../
these slashes indicate that everything between them is a regular expression pattern^
asserts the start of the string[a-zA-Z]
matches any single character in the range a-z or A-Z$
asserts the end of the stringtest()
method returns true if the input matches the pattern, false otherwise
Capitalize given string
To capitalize given string, you can take first character of the string using charAt(0)
and capitalize it with toUpperCase()
.
At the end concatenate it with the rest of the string using slice(1)
const capitalizeStr = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log(capitalizeStr("hello")); // Output: "Hello"
console.log(capitalizeStr("world")); // Output: "World"
Convert Number to Letter
In this task we are required to convert given number to uppercase or lowercase letter.
Example:
1 -> A
2 -> B
3 -> C
or convert to lowercase letters
1 -> a
2 -> b
3 -> c
const numberToLetter = (num) => {
// ASCII value of 'A' is 65, so we add (num - 1) to get the correct letter
return String.fromCharCode(65 + (num - 1));
}
console.log(numberToLetter(1)); // Output: A
console.log(numberToLetter(2)); // Output: B
console.log(numberToLetter(26)); // Output: Z