This website requires JavaScript.
JavaScript Array Methods

9 lines of JavaScript replace 50 lines of code

Minify Javascript code with new commands

7 min read

I. Problem

These are really useful, easy-to-read tips that take advantage of modern JavaScript features to solve common problems. So whether you’re cleaning up your code or just starting a new project, these tricks can help you write more elegant and maintainable code.

Here are 9 such handy tricks that you can start using today. Let’s see what they are!

II. Solution

1. Flatten nested arrays

Have you ever tried flattening a deeply nested array? Previously, it meant lots of complicated loops, temporary arrays, and way too much code. But now it’s done very neatly in one powerful line of code:

Traditional
Modern
function flattenTheHardWay(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flattenTheHardWay(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}

// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

All the hard work is handled by flat(), and adding Infinity tells it to go down any level. Simple, clean, and it actually works.

2. Deep copy object without librarys

Need a true deep copy of an object without using lodash? Here's a library-less solution that handles nested objects, arrays, and even dates:

Traditional
Modern
function manualDeepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj);
  const clone = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    if (Object[.]prototype[.]hasOwnProperty[.]call(obj, key)) {
      clone[key] = manualDeepClone(obj[key]);
    }
  }
  return clone;
}

3. Convert CSV to array of objects

Here's a neat little command line to take CSV data and output an array of manipulable objects, ideal for use in API responses or reading data:

Traditional
Modern
function convertCSVTheHardWay(csv) {
  const lines = csv.split('\n');
  const headers = lines[0].split(',');
  const result = [];
  for (let i = 1; i < lines.length; i++) {
    const obj = {};
    const currentLine = lines[i].split(',');
    for (let j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentLine[j];
    }
    result.push(obj);
  }
  return result;
}

It's an efficient way to do data transformations with a command line, but add some error handling before putting it into production.

4. Remove duplicate elements and sort array

Here is a shorthand command to remove duplicate elements and sort your array at the same time, perfect for cleaning up a dataset:

Traditional
Modern
function cleanArrayManually(arr) {
  const unique = [];
  for (let i = 0; i < arr.length; i++) {
    if (unique.indexOf(arr[i]) === -1) {
      unique.push(arr[i]);
    }
  }
  return unique.sort((a, b) => a - b);
}

The Set will take care of removing duplicates perfectly, and then the spread operator will turn it back into an array. And you just need to call sort() afterwards!

5. DOM Manipulation: Querying and Mutating Multiple Elements

This is a powerful command line that allows you to query and transform multiple DOM elements at once:

Traditional
Modern
function updateElementsManually(selector) {
const elements = document.querySelectorAll(selector);
for (let i = 0; i < elements.length; i++) {
  const el = elements[i];
  el.style.backgroundColor = '[#]007bff';
  el.style.color = 'white';
  el.style.padding = '10px 20px';
  }
}

This works in all modern browsers and saves you from writing repetitive DOM manipulation code.

6. Parallel API calls with clean error handling

Here's another neat line of code that makes parallel calls to the API and handles errors very cleanly.

Traditional
Modern
async function fetchDataManually(urls) {
  const results = [];
  for (const url of urls) {
    try {
      const response = await fetch(url);
      const data = await response.json();
      results.push({ status: 'fulfilled', value: data });
    } catch (error) {
      results.push({ status: 'rejected', reason: error });
    }
  }
  return results;
}

Promise.allSettled is the hero here; it doesn't fail if a request fails, and it returns explicit state information for each call.

7. Date/Time Format: Clean Date Strings Without Libraries

Here's a great command line that converts dates into clean, readable strings without any external libraries:

Traditional
Modern
function formatDateManually(date) {
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const dayName = days[date.getDay()];
  const monthName = months[date.getMonth()];
  const day = date.getDate();
  const year = date.getFullYear();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const ampm = hours >= 12 ? 'PM' : 'AM';
  return ${dayName}, ${monthName} ${day}, ${year} at ${hours % 12}:${minutes.toString().padStart(2, '0')} ${ampm};
}

Intl.DateTimeFormat handles all the heavy lifting, including localization. No more manually building date strings!

8. Event Handling: Debounce Without Bloat

Here's a neat command line to create a debounce version of any function - perfect for handling search input or resizing windows:

Traditional
Modern
function createDebounce(fn, delay) {
  let timeoutId;
  return function debounced(...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      fn.apply(this, args);
      timeoutId = null;
    }, delay);
  };
}

This command line covers all the basic debounce use cases and saves you from calling unnecessary functions, especially when inputs are generated continuously like typing or resizing.

9. Local Storage: Object Storage with Authentication

Here's just another neat line of code to handle storing objects in localStorage with built-in validation and error handling:

Traditional
Modern
function handleLocalStorage(key) {
  return {
    get: function() {
      try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : null;
      } catch (e) {
        console.error('Error reading from localStorage', e);
        return null;
      }
    },
    set: function(data) {
      try {
        localStorage.setItem(key, JSON.stringify(data));
      } catch (e) {
        console.error('Error writing to localStorage', e);
      }
    },
    remove: function() {
      try {
        localStorage.removeItem(key);
      } catch (e) {
        console.error('Error removing from localStorage', e);
      }
    }
  };
}

This wrapper gives you a clean API for localStorage operations and automatically handles all the JSON parsing/serialization.

III. Conclusion

These snippets aren’t just about writing less code – they’re about writing smarter code. Each one solves a common JavaScript challenge in a clean, maintainable way. While these snippets are powerful, remember that readability should always come first. If a single line of code makes your code harder to understand, split it into multiple lines.

  • Tags:
  • javascript
Dec 30, 2024
Previous page
Download specific folder from GitHub
Next page
Event Loop in Nodejs

🍃 Related posts