15 snippets

JavaScript Snippets

Essential JavaScript code snippets for everyday development.

arrays

Remove duplicates from array

Get unique values using Set or filter.

// Using Set (fastest)
const unique = [...new Set(array)];

// Using filter
const unique2 = array.filter((v, i, a) => a.indexOf(v) === i);

// For arrays of objects (by key)
const uniqueByKey = (arr, key) =>
  [...new Map(arr.map(item => [item[key], item])).values()];

Group array by property

Group an array of objects by a specific key.

// Using Object.groupBy (ES2024)
const grouped = Object.groupBy(people, p => p.city);

// Using reduce (older environments)
const grouped2 = array.reduce((acc, item) => {
  const key = item.category;
  (acc[key] ??= []).push(item);
  return acc;
}, {});

Flatten nested arrays

Flatten arrays of any depth.

// Flatten one level
const flat = arr.flat();

// Flatten deeply nested
const deepFlat = arr.flat(Infinity);

// Recursive flatten (custom)
const flatten = (arr) =>
  arr.reduce((acc, val) =>
    Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val),
  []);

Split array into chunks

Divide an array into smaller arrays of a specified size.

function chunk(array, size) {
  const chunks = [];
  for (let i = 0; i < array.length; i += size) {
    chunks.push(array.slice(i, i + size));
  }
  return chunks;
}

// Usage
chunk([1, 2, 3, 4, 5], 2); // [[1,2], [3,4], [5]]

Sort array of objects

Sort objects by one or more properties.

// Sort by string property
users.sort((a, b) => a.name.localeCompare(b.name));

// Sort by number (ascending)
items.sort((a, b) => a.price - b.price);

// Sort by multiple fields
users.sort((a, b) =>
  a.lastName.localeCompare(b.lastName) ||
  a.firstName.localeCompare(b.firstName)
);

objects

Deep clone an object

Create a deep copy without references.

// Best: structuredClone (modern)
const clone = structuredClone(original);

// JSON trick (no functions/undefined/dates)
const clone2 = JSON.parse(JSON.stringify(original));

// Shallow copy (one level only)
const shallow = { ...original };
const shallow2 = Object.assign({}, original);

Deep merge objects

Recursively merge nested objects.

function deepMerge(target, ...sources) {
  for (const source of sources) {
    for (const key of Object.keys(source)) {
      if (source[key] instanceof Object && key in target) {
        Object.assign(source[key], deepMerge(target[key], source[key]));
      }
    }
    Object.assign(target, source);
  }
  return target;
}

// Shallow merge is easy
const merged = { ...defaults, ...overrides };

Pick / Omit object keys

Create an object with only specified keys, or without them.

// Pick specific keys
const pick = (obj, keys) =>
  Object.fromEntries(keys.map(k => [k, obj[k]]));

// Omit specific keys
const omit = (obj, keys) =>
  Object.fromEntries(
    Object.entries(obj).filter(([k]) => !keys.includes(k))
  );

// Usage
pick(user, ['name', 'email']);
omit(user, ['password', 'token']);

async

Parallel async operations

Run multiple promises in parallel with error handling.

// All must succeed
const [users, posts] = await Promise.all([
  fetchUsers(),
  fetchPosts(),
]);

// Some can fail (get results for each)
const results = await Promise.allSettled([
  fetchUsers(),
  fetchPosts(),
  fetchComments(),
]);

const successes = results
  .filter(r => r.status === 'fulfilled')
  .map(r => r.value);

Retry failed async operations

Retry a function with exponential backoff.

async function retry(fn, maxRetries = 3, delay = 1000) {
  for (let i = 0; i <= maxRetries; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === maxRetries) throw err;
      await new Promise(r =>
        setTimeout(r, delay * Math.pow(2, i))
      );
    }
  }
}

// Usage
const data = await retry(() => fetch('/api/data'), 3, 500);

utilities

Debounce function

Delay execution until after a pause in calls.

function debounce(fn, ms = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

// Usage
const search = debounce((query) => {
  fetch(`/api/search?q=${query}`);
}, 300);

input.addEventListener('input', (e) => search(e.target.value));

Throttle function

Limit function execution to once per interval.

function throttle(fn, ms = 300) {
  let lastCall = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall >= ms) {
      lastCall = now;
      return fn(...args);
    }
  };
}

// Usage
window.addEventListener('scroll',
  throttle(() => console.log('scrolled'), 100)
);

strings

Convert string to URL slug

Transform any string into a URL-friendly slug.

function slugify(str) {
  return str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

slugify('Hello World!');   // 'hello-world'
slugify('  Café Résumé '); // 'caf-rsum'

Truncate string with ellipsis

Shorten a string to a max length, adding ellipsis.

function truncate(str, maxLength = 50) {
  if (str.length <= maxLength) return str;
  return str.slice(0, maxLength).trimEnd() + '…';
}

// Truncate at word boundary
function truncateWords(str, maxLength = 50) {
  if (str.length <= maxLength) return str;
  return str.slice(0, str.lastIndexOf(' ', maxLength)) + '…';
}

dom

Copy text to clipboard

Copy text using the modern Clipboard API.

// Modern approach
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log('Copied!');
  } catch (err) {
    console.error('Failed to copy:', err);
  }
}

// Fallback for older browsers
function copyFallback(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}
All Languages