1. Array Deduplication
1
| const uniqueArray = [...new Set([1, 2, 3, 3, 4, 4, 5])];
|
Use ES6 Set and the spread operator to remove duplicates — cleaner and more efficient than loops.
2. Swap Two Variables Quickly
3. Check if Object is Empty
1
| const isEmpty = obj => Object.keys(obj).length === 0;
|
One-liner to check if an object has no properties.
4. Get a Random Element from Array
1
| const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];
|
Great for lottery draws, random displays, etc.
5. Generate Random Integer in Range
1
| const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
|
6. Convert RGB to Hex Color
1
| const rgbToHex = (r, g, b) => '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
|
7. Copy Text to Clipboard
1
| const copyToClipboard = text => navigator.clipboard.writeText(text);
|
8. Detect Mobile Device
1
| const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
|
1
| const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });
|
10. Get URL Query Parameter
1
| const getQueryParam = param => new URLSearchParams(window.location.search).get(param);
|
11. Calculate Array Average
1
| const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
|
12. Check if Element is in Viewport
1 2 3 4 5 6 7 8 9
| const isInViewport = el => { const rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement,clientWidth) ); };
|
13. Flatten Nested Arrays
1
| const flatten = arr => [].concat(...arr.map(item => Array.isArray(item) ? flatten(item) : item));
|
14. Count Occurrences of an Element
1
| const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
|
15. Generate Random Hex Color
1
| const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;
|
16. Check if Date is a Weekend
1
| const isWeekend = date => [0, 6].includes(date.getDay());
|
17. Days Between Two Dates
1
| const daysBetween = (date1, date2) => Math.ceil(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));
|
18. Capitalize First Letter
1
| const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
|
19. Shuffle Array
1
| const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
|
20. Debounce Function
1 2 3 4 5 6 7
| const debounce = (fn, delay) => { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => fn(...args), delay); }; };
|