function reverseString(str) {
return str.split('').reverse().join('');
}
// Example usage:
console.log(reverseString('hello')); // Output: 'olleh'
split('')
breaks the string into an array of characters.reverse()
reverses the array.join('')
joins the array back into a string.
function findLargest(arr) {
return Math.max(...arr);
}
// Example usage:
console.log(findLargest([3, 5, 7, 2, 8])); // Output: 8
Math.max(...arr)
spreads the array elements as individual arguments to the Math.max
function, which returns the largest number.
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
// Example usage:
console.log(isPalindrome('madam')); // Output: true
console.log(isPalindrome('hello')); // Output: false
function findMissingNumber(arr, n) {
const total = (n * (n + 1)) / 2; // Sum of numbers from 1 to N
const sum = arr.reduce((acc, num) => acc + num, 0);
return total - sum;
}
// Example usage:
console.log(findMissingNumber([1, 2, 4, 5], 5)); // Output: 3
(n * (n + 1)) / 2
.
function firstNonRepeatingCharacter(str) {
const frequency = {};
for (let i = 0; i < str.length; i++) {
frequency[str[i]] = (frequency[str[i]] || 0) + 1;
}
for (let i = 0; i < str.length; i++) {
if (frequency[str[i]] === 1) {
return str[i];
}
}
return null;
}
// Example usage:
console.log(firstNonRepeatingCharacter('swiss')); // Output: 'w'
console.log(firstNonRepeatingCharacter('aabbcc')); // Output: null
function mergeSortedArrays(arr1, arr2) {
let i = 0;
let j = 0;
let mergedArray = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
mergedArray.push(arr1[i]);
i++;
} else {
mergedArray.push(arr2[j]);
j++;
}
}
return mergedArray.concat(arr1.slice(i), arr2.slice(j));
}
// Example usage:
console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6]
i
and j
, are used to traverse the two arrays.arr1[i]
and arr2[j]
is pushed to the mergedArray
until one of the arrays is exhausted.
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func(...args);
}, delay);
};
}
// Example usage:
const debouncedFunction = debounce(() => console.log('Debounced!'), 1000);
debouncedFunction(); // The message will be logged after 1 second.
debounce
function ensures that the provided function is only invoked after the given delay
has passed since the last invocation.
function flattenArray(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
acc.push(...flattenArray(item)); // Recursively flatten nested arrays
} else {
acc.push(item);
}
return acc;
}, []);
}
// Example usage:
console.log(flattenArray([1, [2, 3], [4, [5, 6]], 7])); // Output: [1, 2, 3, 4, 5, 6, 7]
reduce
function is used to iterate over the array.
function removeDuplicates(arr) {
return [...new Set(arr)];
}
// Example usage:
console.log(removeDuplicates([1, 2, 3, 1, 2, 4])); // Output: [1, 2, 3, 4]
Set
will automatically eliminate duplicates since sets only store unique values. Then, we use the spread operator (...
) to convert the Set
back into an array.
function secondLargest(arr) {
let first = -Infinity;
let second = -Infinity;
for (let num of arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num !== first) {
second = num;
}
}
return second === -Infinity ? null : second;
}
// Example usage:
console.log(secondLargest([3, 5, 7, 2, 8])); // Output: 7
console.log(secondLargest([3, 3, 3])); // Output: null
function sumInRange(start, end) {
let sum = 0;
for (let i = start; i <= end; i++) {
sum += i;
}
return sum;
}
// Example usage:
console.log(sumInRange(1, 5)); // Output: 15 (1 + 2 + 3 + 4 + 5)
for
loop to iterate from start
to end
and accumulate the sum of numbers in that range.
function countOccurrences(arr, value) {
return arr.filter(item => item === value).length;
}
// Example usage:
console.log(countOccurrences([1, 2, 2, 3, 2], 2)); // Output: 3
filter()
method to create an array of elements that match the specified value, and then return the length of that array, which gives us the count of occurrences.
function intersection(arr1, arr2) {
return arr1.filter(item => arr2.includes(item));
}
// Example usage:
console.log(intersection([1, 2, 3], [3, 4, 5])); // Output: [3]
filter()
method is used on the first array to keep only the elements that are also found in the second array using the includes()
method.
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(isPrime(7)); // Output: true
console.log(isPrime(10)); // Output: false
2
to the square root of num
to check for any divisors. If any number divides num
, it's not prime.
function findMissingCharacter(str1, str2) {
const sortedStr1 = str1.split('').sort().join('');
const sortedStr2 = str2.split('').sort().join('');
for (let i = 0; i < sortedStr1.length; i++) {
if (sortedStr1[i] !== sortedStr2[i]) {
return sortedStr1[i];
}
}
return sortedStr1[sortedStr1.length - 1]; // If the missing character is the last one
}
// Example usage:
console.log(findMissingCharacter('abcd', 'abc')); // Output: 'd'
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
func(...args);
lastCall = now;
}
};
}
// Example usage:
const throttledFunc = throttle(() => console.log('Throttled!'), 1000);
throttledFunc(); // Will log 'Throttled!' immediately
throttledFunc(); // Will be ignored if less than 1 second passed
throttle
function ensures that the wrapped function is only executed once within the specified time interval (delay
). If it's called multiple times within that interval, only the first call is executed.