Compare Arrays
arrayobjectcompareequal
const compareArrays = (a, b) => {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
return a.every((v, i) =>
Array.isArray(v) && Array.isArray(b[i]) ? compareArrays(v, b[i]) :
typeof v === "object" && typeof b[i] === "object" ? compareObjects(v, b[i]) :
v === b[i]
);
};
const compareObjects = (a, b) => {
if (typeof a !== "object" || typeof b !== "object" || Object.keys(a).length !== Object.keys(b).length) return false;
return Object.keys(a).every(k =>
Array.isArray(a[k]) && Array.isArray(b[k]) ? compareArrays(a[k], b[k]) :
typeof a[k] === "object" && typeof b[k] === "object" ? compareObjects(a[k], b[k]) :
a[k] === b[k]
);
};
// Usage:
compareArrays([1, 2, 3], [1, 2, 3]); // Returns: true
compareArrays([1, 2, 3], [3, 2, 1]); // Returns: false
compareArrays([{a:1}], [{a:1}]); // Returns: true
compareArrays([{a:1}], null); // Returns: false
...
Partition Array
arraypartitionreduce
const partition = (arr, callback) =>
arr.reduce(
([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),
[[], []]
);
// Usage:
const numbers = [1, 2, 3, 4, 5, 6];
const isEven = (n) => n % 2 === 0;
partition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]
...
Remove Duplicates
arraydeduplicate
const removeDuplicates = (arr) => [...new Set(arr)];
// Usage:
const numbers = [1, 2, 2, 3, 4, 4, 5];
removeDuplicates(numbers); // Returns: [1, 2, 3, 4, 5]
...
Remove Falsy Values
arrayfalsyfilter
const removeFalsy = (arr) => arr.filter(Boolean);
// Usage:
const array = [0, 1, false, 2, "", 3, null];
removeFalsy(array); // Returns: [1, 2, 3]
...
Shuffle Array
arrayshuffle
function shuffleArray(array) {
for (let i = array.length - 1; i >= 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// Usage:
const array = [1, 2, 3, 4, 5];
shuffleArray(array); // Shuffles `array` in place
...
Zip Arrays
arraymap
const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);
// Usage:
const arr1 = ['a', 'b', 'c'];
const arr2 = [1, 2, 3];
console.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]
...
Hello, World!
printinghello-world
console.log("Hello, World!"); // Prints Hello, World! to the console
...
Hex to RGB Color
colorconversion
function hexToRgb(hex) {
let sanitizedHex = hex.startsWith("#") ? hex.slice(1) : hex;
if (sanitizedHex.length === 3) {
sanitizedHex = [...sanitizedHex].map((char) => char + char).join("");
}
const bigint = parseInt(sanitizedHex, 16);
return {
r: (bigint >> 16) & 0xff,
g: (bigint >> 8) & 0xff,
b: bigint & 0xff,
};
}
// Usage:
console.log(hexToRgb("#ff5733")); // { r: 255, g: 87, b: 51 }
console.log(hexToRgb("#ffff")); // { r: 0, g: 255, b: 255 }
...
HSL to RGB Color
colorconversion
function hslToRgb(h, s, l) {
s /= 100;
l /= 100;
const c = (1 - Math.abs(2 * l - 1)) * s;
const x = c * (1 - Math.abs((h / 60) % 2 - 1));
const m = l - c / 2;
const [r, g, b] =
h < 60 ? [c, x, 0] :
h < 120 ? [x, c, 0] :
h < 180 ? [0, c, x] :
h < 240 ? [0, x, c] :
h < 300 ? [x, 0, c] :
[c, 0, x];
return {
r: Math.round((r + m) * 255),
g: Math.round((g + m) * 255),
b: Math.round((b + m) * 255),
};
}
// Usage:
console.log(hslToRgb(14, 100, 60)); // { r: 255, g: 87, b: 51 }
console.log(hslToRgb(0, 0, 100)); // { r: 255, g: 255, b: 255 }
...
RGB to Hex Color
colorconversion
function rgbToHex(r, g, b) {
const toHex = (n) => {
const hex = n.toString(16);
return hex.length === 1 ? "0" + hex : hex;
};
return "#" + toHex(r) + toHex(g) + toHex(b);
}
// Usage:
console.log(rgbToHex(255, 128, 0)); // Output: "#ff8000"
console.log(rgbToHex(0, 255, 0)); // Output: "#00ff00"
...
RGB to HSL Color
colorconversion
function rgbToHsl(r, g, b) {
[r, g, b] = [r, g, b].map((v) => v / 255);
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - min;
const l = (max + min) / 2;
if (delta === 0) return { h: 0, s: 0, l: Math.round(l * 100) };
const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
const h =
max === r ? ((g - b) / delta + (g < b ? 6 : 0)) :
max === g ? (b - r) / delta + 2 :
(r - g) / delta + 4;
return {
h: Math.round(h * 60),
s: Math.round(s * 100),
l: Math.round(l * 100),
};
}
// Usage:
console.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }
console.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }
...
Check Leap Year
dateleap-year
const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
// Usage:
isLeapYear(2024); // Returns: true
isLeapYear(2023); // Returns: false
...
Convert to Unix Timestamp
dateunixtimestamp
function convertToUnixSeconds(input) {
if (typeof input === 'string') {
if (!input.trim()) {
throw new Error('Date string cannot be empty or whitespace');
}
} else if (!input) {
throw new Error('Input is required');
}
let date;
if (typeof input === 'string') {
date = new Date(input);
} else if (input instanceof Date) {
date = input;
} else {
throw new Error('Input must be a valid date string or Date object');
}
if (isNaN(date.getTime())) {
throw new Error('Invalid date provided');
}
return Math.floor(date.getTime() / 1000);
}
// Usage:
convertToUnixSeconds('2025-01-01T12:00:00Z'); // Returns: 1735732800
convertToUnixSeconds(new Date('2025-01-01T12:00:00Z')); // Returns: 1735732800
convertToUnixSeconds(new Date()); // Returns: Current Unix timestamp in seconds
...
Format Date
dateformat
const formatDate = (date) => date.toISOString().split('T')[0];
// Usage:
formatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'
...
Get Day of the Year
dateday-of-year
const getDayOfYear = (date) => {
const startOfYear = new Date(date.getFullYear(), 0, 0);
const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;
return Math.floor(diff / (1000 * 60 * 60 * 24));
};
// Usage:
getDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year)
...
Get Days in Month
datedays-in-month
const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
// Usage:
getDaysInMonth(2024, 1); // Returns: 29 (February in a leap year)
getDaysInMonth(2023, 1); // Returns: 28
...
Get Time Difference
datetime-difference
const getTimeDifference = (date1, date2) => {
const diff = Math.abs(date2 - date1);
return Math.ceil(diff / (1000 * 60 * 60 * 24));
};
// Usage:
const date1 = new Date('2024-01-01');
const date2 = new Date('2024-12-31');
getTimeDifference(date1, date2); // Returns: 365
...
Relative Time Formatter
datetimerelativefuturepast
const getRelativeTime = (date) => {
const now = Date.now();
const diff = date.getTime() - now;
const seconds = Math.abs(Math.floor(diff / 1000));
const minutes = Math.abs(Math.floor(seconds / 60));
const hours = Math.abs(Math.floor(minutes / 60));
const days = Math.abs(Math.floor(hours / 24));
const years = Math.abs(Math.floor(days / 365));
if (Math.abs(diff) < 1000) return 'just now';
const isFuture = diff > 0;
if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;
if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;
if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;
if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;
return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;
}
// Usage:
const pastDate = new Date('2021-12-29 13:00:00');
const futureDate = new Date('2099-12-29 13:00:00');
getRelativeTime(pastDate); // x years ago
getRelativeTime(new Date()); // just now
getRelativeTime(futureDate); // in x years
...
Start of the Day
datestart-of-day
const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));
// Usage:
const today = new Date();
startOfDay(today); // Returns: Date object for midnight
...
Change Element Style
domstyle
const changeElementStyle = (element, styleObj) => {
Object.entries(styleObj).forEach(([property, value]) => {
element.style[property] = value;
});
};
// Usage:
const element = document.querySelector('.my-element');
changeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });
...
Remove Element
domremove
const removeElement = (element) => {
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
};
// Usage:
const element = document.querySelector('.my-element');
removeElement(element);
...
Compose Functions
functioncompose
const compose = (...funcs) => (initialValue) => {
return funcs.reduce((acc, func) => func(acc), initialValue);
};
// Usage:
const add2 = (x) => x + 2;
const multiply3 = (x) => x * 3;
const composed = compose(multiply3, add2);
composed(5); // Returns: 17 ((5 * 3) + 2)
...
Curry Function
curryfunction
const curry = (func) => {
const curried = (...args) => {
if (args.length >= func.length) {
return func(...args);
}
return (...nextArgs) => curried(...args, ...nextArgs);
};
return curried;
};
// Usage:
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // Returns: 6
curriedAdd(1, 2)(3); // Returns: 6
...
Debounce Function
debounceperformance
const debounce = (func, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
};
// Usage:
window.addEventListener(
'resize',
debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms
);
...
Get Contrast Color
colorhexcontrastbrightness
const getContrastColor = (hexColor) => {
// Expand short hex color to full format
if (hexColor.length === 4) {
hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;
}
const r = parseInt(hexColor.slice(1, 3), 16);
const g = parseInt(hexColor.slice(3, 5), 16);
const b = parseInt(hexColor.slice(5, 7), 16);
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
return brightness >= 128 ? "#000000" : "#FFFFFF";
};
// Usage:
getContrastColor('#fff'); // Returns: #000000 (black)
getContrastColor('#123456'); // Returns: #FFFFFF (white)
getContrastColor('#ff6347'); // Returns: #000000 (black)
getContrastColor('#f4f'); // Returns: #000000 (black)
...
Memoize Function
memoizationoptimization
const memoize = (func) => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = func(...args);
cache.set(key, result);
return result;
};
};
// Usage:
const factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));
factorial(5); // Returns: 120
factorial(5); // Returns: 120 (retrieved from cache)
...
Once Function
functiononce
const once = (func) => {
let called = false;
return (...args) => {
if (!called) {
called = true;
return func(...args);
}
};
};
// Usage:
const initialize = once(() => console.log('Initialized!'));
initialize(); // Output: Initialized!
initialize(); // No output
...
Rate Limit Function
functionrate-limiting
const rateLimit = (func, limit, timeWindow) => {
let queue = [];
setInterval(() => {
if (queue.length) {
const next = queue.shift();
func(...next.args);
}
}, timeWindow);
return (...args) => {
if (queue.length < limit) {
queue.push({ args });
}
};
};
// Usage:
const fetchData = () => console.log('Fetching data...');
const rateLimitedFetch = rateLimit(fetchData, 2, 1000);
setInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds
...
Repeat Function Invocation
functionrepeat
const times = (func, n) => {
Array.from(Array(n)).forEach(() => {
func();
});
};
// Usage:
const randomFunction = () => console.log('Function called!');
times(randomFunction, 3); // Logs 'Function called!' three times
...
Sleep Function
javascriptsleepdelayutilitypromises
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Usage:
console.log('Hello');
await sleep(2000); // Waits for 2 seconds
console.log('World!');
...
Add Item to localStorage
localStoragestorage
const addToLocalStorage = (key, value) => {
localStorage.setItem(key, JSON.stringify(value));
};
// Usage:
addToLocalStorage('user', { name: 'John', age: 30 });
...
Check if Item Exists in localStorage
localStoragestorage
const isItemInLocalStorage = (key) => {
return localStorage.getItem(key) !== null;
};
// Usage:
console.log(isItemInLocalStorage('user')); // Output: true or false
...
Retrieve Item from localStorage
localStoragestorage
const getFromLocalStorage = (key) => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
};
// Usage:
getFromLocalStorage('user'); // Returns: { name: 'John', age: 30 }
...
Combinations
mathnumber-theoryalgebra
function combinations(n, r) {
if (n < 0 || r < 0 || n < r) {
throw new Error('Invalid input: n and r must be non-negative and n must be greater than or equal to r.');
}
function factorial(x) {
if (x === 0 || x === 1) return 1;
let result = 1;
for (let i = 2; i <= x; i++) {
result *= i;
}
return result;
}
const numerator = factorial(n);
const denominator = factorial(r) * factorial(n - r);
return numerator / denominator;
}
// Usage:
combinations(24,22); // Returns: 276
combinations(5,3); // Returns: 10
...
Cross Product
mathvector-algebra
function crossProduct(a, b) {
if (a.length !== 3 || b.length !== 3) {
throw new Error('Vectors must be 3-dimensional');
}
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]
];
}
// Usage:
crossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3]
...
Dot Product
mathvector-algebra
function dotProduct(a, b) {
if (a.length !== b.length) {
throw new Error('Vectors must be of the same length');
}
return a.reduce((sum, value, index) => sum + value * b[index], 0);
}
// Usage:
dotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32
...
Error function
math
function erf(x) {
const sign = Math.sign(x);
const absX = Math.abs(x);
const t = 1 / (1 + 0.3275911 * absX);
const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429;
const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))));
return sign * (1 - poly * Math.exp(-absX * absX));
}
// Usage:
erf(-1); // Returns: -0.8427006897475899
erf(1); // Returns: 0.8427006897475899
...
Greatest Common Divisor
mathdivisionnumber-theoryalgebra
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
// Usage:
gcd(1920, 1080); // Returns: 120
gcd(1920, 1200); // Returns: 240
gcd(5,12); // Returns: 1
...
Least common multiple
mathnumber-theoryalgebra
function lcm(a, b) {
function gcd(x, y) {
while (y !== 0) {
const temp = y;
y = x % y;
x = temp;
}
return Math.abs(x);
}
return Math.abs(a * b) / gcd(a, b);
}
// Usage:
lcm(12,16); // Returns: 48
lcm(8,20); // Returns: 40
lcm(16,17); // Returns: 272
...
Linear Mapping
mathnumber-theoryalgebra
function linearMapping(value, minIn, maxIn, minOut, maxOut) {
return (value - minIn) * (maxOut - minOut)/(maxIn - minIn) + minOut
}
// Usage:
linearMapping(value, 0, 1, 0, 255) // remaps the value from (0,1) to (0,255)
linearMapping(value, 0, PI*2, 0, 360) // remaps the value from rad to deg
linearMapping(value, -1, 1, 1, 8) // remaps the value from (-1,1) to (1,8)
...
Matrix Multiplication
mathmatrix-algebra
function matrixMultiply(A, B) {
const rowsA = A.length;
const colsA = A[0].length;
const rowsB = B.length;
const colsB = B[0].length;
if (colsA !== rowsB) {
throw new Error('Number of columns of A must equal the number of rows of B');
}
let result = Array.from({ length: rowsA }, () => Array(colsB).fill(0));
for (let i = 0; i < rowsA; i++) {
for (let j = 0; j < colsB; j++) {
for (let k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
// Usage:
matrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns: [[19, 22], [43, 50]]
...
Modular Inverse
mathnumber-theoryalgebra
function modInverse(a, m) {
function extendedGCD(a, b) {
if (b === 0) {
return { gcd: a, x: 1, y: 0 };
}
const { gcd, x: x1, y: y1 } = extendedGCD(b, a % b);
const x = y1;
const y = x1 - Math.floor(a / b) * y1;
return { gcd, x, y };
}
const { gcd, x } = extendedGCD(a, m);
if (gcd !== 1) {
return null;
}
return (x % m + m) % m;
}
// Usage:
modInverse(3, 26); // Returns: 9
modInverse(10, 17); // Returns: 12
modInverse(6, 9); // Returns: null
...
Prime Number
mathnumber-theoryalgebra
function isPrime(num) {
if (num <= 1) return false; // 0 and 1 are not prime numbers
if (num <= 3) return true; // 2 and 3 are prime numbers
if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3
// Check divisors from 5 to √num, skipping multiples of 2 and 3
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) return false;
}
return true;
}
// Usage:
isPrime(69); // Returns: false
isPrime(17); // Returns: true
...
Convert Number to Currency
numbercurrency
const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
}).format(num);
};
// Usage:
convertToCurrency(1234567.89); // Returns: '$1,234,567.89'
convertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €'
...
Convert Number to Roman Numerals
numberroman
const numberToRoman = (num) => {
const romanNumerals = {
1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',
90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'
};
let result = '';
Object.keys(romanNumerals).reverse().forEach(value => {
while (num >= value) {
result += romanNumerals[value];
num -= value;
}
});
return result;
};
// Usage:
numberToRoman(1994); // Returns: 'MCMXCIV'
numberToRoman(58); // Returns: 'LVIII'
...
Convert to Scientific Notation
numberscientific
const toScientificNotation = (num) => {
if (isNaN(num)) {
throw new Error('Input must be a number');
}
if (num === 0) {
return '0e+0';
}
const exponent = Math.floor(Math.log10(Math.abs(num)));
const mantissa = num / Math.pow(10, exponent);
return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;
};
// Usage:
toScientificNotation(12345); // Returns: '1.23e+4'
toScientificNotation(0.0005678); // Returns: '5.68e-4'
toScientificNotation(1000); // Returns: '1.00e+3'
toScientificNotation(0); // Returns: '0e+0'
toScientificNotation(-54321); // Returns: '-5.43e+4'
...
Format File Size
formatsize
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Usage:
console.log(formatFileSize(1234)); // Output: "1.21 KB"
console.log(formatFileSize(1234567)); // Output: "1.18 MB"
...
Format Number with Commas
numberformat
const formatNumberWithCommas = (num) => {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
// Usage:
formatNumberWithCommas(1000); // Returns: '1,000'
formatNumberWithCommas(1234567); // Returns: '1,234,567'
formatNumberWithCommas(987654321); // Returns: '987,654,321'
...
Number Formatter
numberformat
const nFormatter = (num) => {
if (!num) return;
num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));
const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];
let index = 0;
while (num >= 1000 && index < suffixes.length - 1) {
num /= 1000;
index++;
}
return num.toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];
};
// Usage:
nFormatter(1234567); // Returns: '1.23M'
...
Number to Words Converter
numberwords
const numberToWords = (num) => {
const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];
if (num < 20) return below20[num];
let words = '';
for (let i = 0; num > 0; i++) {
if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;
if (num % 100 >= 20) {
words = tens[Math.floor(num / 10)] + ' ' + words;
num %= 10;
}
if (num < 20) words = below20[num] + ' ' + words;
num = Math.floor(num / 100);
}
return words.trim();
};
// Usage:
numberToWords(123); // Returns: 'One Hundred Twenty Three'
numberToWords(2045); // Returns: 'Two Thousand Forty Five'
...
Check if Object is Empty
objectcheckempty
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
// Usage:
isEmptyObject({}); // Returns: true
isEmptyObject({ a: 1 }); // Returns: false
...
Compare Two Objects Shallowly
objectcompareshallow
function shallowEqual(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every(key => obj1[key] === obj2[key]);
}
// Usage:
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
const obj3 = { a: 1, b: 3 };
shallowEqual(obj1, obj2); // Returns: true
shallowEqual(obj1, obj3); // Returns: false
...
Convert Object to Query String
objectquery stringurl
function toQueryString(obj) {
return Object.entries(obj)
.map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))
.join('&');
}
// Usage:
const params = { search: 'test', page: 1 };
toQueryString(params); // Returns: 'search=test&page=1'
...
Count Properties in Object
objectcountproperties
function countProperties(obj) {
return Object.keys(obj).length;
}
// Usage:
const obj = { a: 1, b: 2, c: 3 };
countProperties(obj); // Returns: 3
...
Deep Clone Object
objectclone
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
// Usage:
const original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
const cloned = deepClone(original);
console.log(cloned); // Output: 'original' but cloned
...
Filter Object
objectfilter
export const filterObject = (object = {}) =>
Object.fromEntries(
Object.entries(object)
.filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))
);
// Usage:
const obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };
filterObject(obj1); // Returns: { a: 1, d: 4 }
const obj2 = { x: 0, y: false, z: 'Hello', w: [] };
filterObject(obj2); // Returns: { z: 'Hello' }
const obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };
filterObject(obj3); // Returns: { name: 'John', address: { city: 'New York' } }
const obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };
filterObject(obj4); // Returns: { e: 'Valid' }
...
Flatten Nested Object
objectflatten
function flattenObject(obj, prefix = '') {
return Object.keys(obj).reduce((acc, key) => {
const fullPath = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
Object.assign(acc, flattenObject(obj[key], fullPath));
} else {
acc[fullPath] = obj[key];
}
return acc;
}, {});
}
// Usage:
const nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };
flattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 }
...
Freeze Object
objectfreezeimmutable
function freezeObject(obj) {
return Object.freeze(obj);
}
// Usage:
const obj = { a: 1, b: 2 };
const frozenObj = freezeObject(obj);
frozenObj.a = 42; // This will fail silently in strict mode.
frozenObj.a; // Returns: 1
...
Get Nested Value
objectnested
const getNestedValue = (obj, path) => {
const keys = path.split('.');
return keys.reduce((currentObject, key) => {
return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;
}, obj);
};
// Usage:
const obj = { a: { b: { c: 42 } } };
getNestedValue(obj, 'a.b.c'); // Returns: 42
...
Invert Object Keys and Values
objectinvert
function invertObject(obj) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [value, key])
);
}
// Usage:
const obj = { a: 1, b: 2, c: 3 };
invertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }
...
Merge Objects Deeply
objectmergedeep
function deepMerge(...objects) {
return objects.reduce((acc, obj) => {
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object' && obj[key] !== null) {
acc[key] = deepMerge(acc[key] || {}, obj[key]);
} else {
acc[key] = obj[key];
}
});
return acc;
}, {});
}
// Usage:
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
deepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 }
...
Omit Keys from Object
objectomit
function omitKeys(obj, keys) {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => !keys.includes(key))
);
}
// Usage:
const obj = { a: 1, b: 2, c: 3 };
omitKeys(obj, ['b', 'c']); // Returns: { a: 1 }
...
Pick Keys from Object
objectpick
function pickKeys(obj, keys) {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => keys.includes(key))
);
}
// Usage:
const obj = { a: 1, b: 2, c: 3 };
pickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 }
...
Unique By Key
arrayunique
const uniqueByKey = (key, arr) =>
arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));
// Usage:
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' }
];
uniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
...
Capitalize String
stringcapitalize
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// Usage:
capitalize('hello'); // Returns: 'Hello'
...
Check if String is a Palindrome
checkpalindromestring
function isPalindrome(str) {
const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleanStr === cleanStr.split('').reverse().join('');
}
// Example usage:
isPalindrome('A man, a plan, a canal, Panama'); // Returns: true
...
Convert String to Camel Case
stringcasecamelCase
function toCamelCase(str) {
return str.replace(/\W+(.)/g, (match, chr) => chr.toUpperCase());
}
// Usage:
toCamelCase('hello world test'); // Returns: 'helloWorldTest'
...
Convert String to Param Case
stringcaseparamCase
function toParamCase(str) {
return str.toLowerCase().replace(/\s+/g, '-');
}
// Usage:
toParamCase('Hello World Test'); // Returns: 'hello-world-test'
...
Convert String to Pascal Case
stringcasepascalCase
function toPascalCase(str) {
return str.replace(/\b\w/g, (s) => s.toUpperCase()).replace(/\W+(.)/g, (match, chr) => chr.toUpperCase());
}
// Usage:
toPascalCase('hello world test'); // Returns: 'HelloWorldTest'
...
Convert String to Snake Case
stringcasesnake_case
function toSnakeCase(str) {
return str.replace(/([a-z])([A-Z])/g, '$1_$2')
.replace(/\s+/g, '_')
.toLowerCase();
}
// Usage:
toSnakeCase('Hello World Test'); // Returns: 'hello_world_test'
...
Convert String to Title Case
stringcasetitleCase
function toTitleCase(str) {
return str.toLowerCase().replace(/\b\w/g, (s) => s.toUpperCase());
}
// Usage:
toTitleCase('hello world test'); // Returns: 'Hello World Test'
...
Convert Tabs to Spaces
stringtabsspaces
function tabsToSpaces(str, spacesPerTab = 4) {
return str.replace(/\t/g, ' '.repeat(spacesPerTab));
}
// Usage:
tabsToSpaces('Hello\tWorld', 2); // Returns: 'Hello World'
...
Count Words in a String
stringmanipulationword countcount
function countWords(str) {
return str.trim().split(/\s+/).length;
}
// Usage:
countWords('Hello world! This is a test.'); // Returns: 6
...
Data with Prefix
dataprefixpostfixformat
const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {
return data ? `${prefix}${data}${postfix}` : fallback;
};
// Usage:
dataWithPrefix('123', '-', '(', ')'); // Returns: '(123)'
dataWithPrefix('', '-', '(', ')'); // Returns: '-'
dataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello'
dataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A'
...
Extract Initials from Name
stringinitialsname
function getInitials(name) {
return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');
}
// Usage:
getInitials('John Doe'); // Returns: 'JD'
...
Generate UUID
uuidgeneratestring
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Usage:
console.log(generateUUID()); // Output: "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5"
...
Mask Sensitive Information
stringmasksensitive
function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {
return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));
}
// Usage:
maskSensitiveInfo('123456789', 4); // Returns: '1234*****'
maskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############'
...
Pad String on Both Sides
stringpadmanipulation
function padString(str, length, char = ' ') {
const totalPad = length - str.length;
const padStart = Math.floor(totalPad / 2);
const padEnd = totalPad - padStart;
return char.repeat(padStart) + str + char.repeat(padEnd);
}
// Usage:
padString('hello', 10, '*'); // Returns: '**hello***'
...
Random string
functionrandom
function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
}
makeid(3); // Returns: gDs (Random)
makeid(5, "1234" /* (optional) */); // Returns: "35453" (Random)
...
Remove All Whitespace
stringwhitespace
function removeWhitespace(str) {
return str.replace(/\s+/g, '');
}
// Usage:
removeWhitespace('Hello world!'); // Returns: 'Helloworld!'
...
Remove Vowels from a String
stringremovevowels
function removeVowels(str) {
return str.replace(/[aeiouAEIOU]/g, '');
}
// Usage:
removeVowels('Hello World'); // Returns: 'Hll Wrld'
...
Reverse String
stringreverse
const reverseString = (str) => str.split('').reverse().join('');
// Usage:
reverseString('hello'); // Returns: 'olleh'
...
Slugify String
stringslug
const slugify = (string, separator = "-") => {
return string
.toString() // Cast to string (optional)
.toLowerCase() // Convert the string to lowercase letters
.trim() // Remove whitespace from both sides of a string (optional)
.replace(/\s+/g, separator) // Replace spaces with {separator}
.replace(/[^\w\-]+/g, "") // Remove all non-word chars
.replace(/\_/g, separator) // Replace _ with {separator}
.replace(/\-\-+/g, separator) // Replace multiple - with single {separator}
.replace(/\-$/g, ""); // Remove trailing -
};
// Usage:
const title = "Hello, World! This is a Test.";
slugify(title); // Returns: 'hello-world-this-is-a-test'
slugify(title, "_"); // Returns: 'hello_world_this_is_a_test'
...
Truncate Text
stringtruncatetext
const truncateText = (text = '', maxLength = 50) => {
return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;
};
// Usage:
const title = "Hello, World! This is a Test.";
truncateText(title); // Returns: 'Hello, World! This is a Test.'
truncateText(title, 10); // Returns: 'Hello, Wor...'
...