10 JavaScript One-Liners That Will Save You Time
These aren't just clever tricks — I use them in production code.
1. Remove Duplicates from Array
const unique = [...new Set([1, 2, 3, 2, 1, 4])];
// [1, 2, 3, 4]
// With objects (by property)
const uniqueById = [...new Map(arr.map(item => [item.id, item])).values()];
2. Deep Clone
const clone = JSON.parse(JSON.stringify(obj));
// Works for JSON-safe data. For complex objects, use structuredClone():
const clone = structuredClone(obj); // Native, handles more types
3. Flatten Array
const flat = [1, [2, [3, [4]]]].flat(Infinity);
// [1, 2, 3, 4]
// Map + flatten in one step
const results = items.flatMap(item => item.tags);
4. Random Element
const random = arr[Math.floor(Math.random() * arr.length)];
const randomColor = ['#ff0', '#f00', '#0f0', '#00f'][Math.floor(Math.random() * 4)];
5. Shuffle Array
const shuffle = arr => [...arr].sort(() => Math.random() - 0.5);
// Note: Fisher-Yates is more random, but this is good enough for UI
// True random (Fisher-Yates)
const shuffle = arr => {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
6. Capitalize String
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize('hello world'); // "Hello world"
// Title case all words
const titleCase = str => str.replace(/\b\w/g, c => c.toUpperCase());
titleCase('the quick brown fox'); // "The Quick Brown Fox"
7. Check if Array is Empty
const isEmpty = arr => Array.isArray(arr) && arr.length === 0;
isEmpty([]); // true
isEmpty([1, 2]); // false
isEmpty(null); // false
isEmpty('abc'); // false
8. Count Occurrences
const countBy = (arr, key) => arr.reduce((acc, item) => {
const k = typeof key === 'function' ? key(item) : item[key];
acc[k] = (acc[k] || 0) + 1;
return acc;
}, {});
countBy(['a', 'b', 'a', 'c', 'a', 'b']); // { a: 3, b: 2, c: 1 }
countBy(users, 'role'); // { admin: 2, user: 5 }
9. Group By Property
const groupBy = (arr, key) => arr.reduce((acc, item) => {
(acc[item[key]] ??= []).push(item);
return acc;
}, {});
groupBy(
[{ type: 'a', val: 1 }, { type: 'b', val: 2 }, { type: 'a', val: 3 }],
'type'
);
// { a: [{ type: 'a', val: 1 }, { type: 'a', val: 3 }], b: [{ type: 'b', val: 2 }] }
10. Debounce and Throttle
// Debounce: Wait until user STOPS calling (search input)
const debounce = (fn, ms) => {
let timer;
return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); };
};
const search = debounce(query => fetchResults(query), 300);
input.addEventListener('input', e => search(e.target.value));
// Throttle: Call at most once per interval (scroll handler)
const throttle = (fn, ms) => {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= ms) { last = now; fn(...args); }
};
};
const onScroll = throttle(() => checkLazyLoad(), 200);
window.addEventListener('scroll', onScroll);
Bonus: More Useful One-Liners
// Range of numbers
const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => start + i);
range(1, 5); // [1, 2, 3, 4, 5]
// Chunk array
const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));
chunk([1, 2, 3, 4, 5, 6, 7], 3); // [[1,2,3], [4,5,6], [7]]
// Zip two arrays
const zip = (a, b) => a.map((v, i) => [v, b[i]]);
zip([1, 2, 3], ['a', 'b', 'c']); // [[1,'a'], [2,'b'], [3,'c']]
// Pick properties from object
const pick = (obj, keys) => Object.fromEntries(keys.filter(k => k in obj).map(k => [k, obj[k]]));
pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { a: 1, c: 3 }
// Omit properties from object
const omit = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));
omit({ a: 1, b: 2, c: 3 }, ['b']); // { a: 1, c: 3 }
// Is empty (works for objects, arrays, strings)
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
isEmpty(null); // true
isEmpty({}); // true
isEmpty([]); // true
isEmpty(''); // true
isEmpty({ a: 1 }); // false
// Sleep
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
await sleep(1000); // Wait 1 second
// Format number with commas
const formatNum = num => num.toLocaleString();
formatNum(1234567); // "1,234,567"
// Convert bytes to readable
const bytes = b => b < 1024 ? b + 'B' : b < 1048576 ? (b/1024).toFixed(1) + 'KB' : (b/1048576).toFixed(1) + 'MB';
bytes(1536); // "1.5KB"
bytes(1048576); // "1.0MB"
Which one-liner do you use most? Got a better version?
Follow @armorbreak for more JavaScript content.
Top comments (0)