Home Web Front-end JS Tutorial avaScript One-Liners That Replace Lines of Code

avaScript One-Liners That Replace Lines of Code

Dec 12, 2024 am 11:06 AM

avaScript One-Liners That Replace Lines of Code

We have all, at one time or another, looked at some horrid wall of JavaScript code cursing silently within ourselves, knowing pretty well that there should be a better way.

After some time spent learning, I have found some neat one-liners that will obliterate many lines of verbose code.

These are truly useful, readable tips that take advantage of modern JavaScript features for tackling common problems.

So, whether you are cleaning up code or just starting a fresh project, these tricks can help with more elegant and maintainable code.

Here are 9 such nifty one-liners you can use today.

Flattening a Nested Array

Ever tried flattening an array that goes so deep? Back in the day, that meant lots of complicated multiple loops, temporary arrays, and altogether too much code.

But now it's executed very nicely in a powerful single-liner:

const flattenArray = arr => arr.flat(Infinity);

const nestedArray = [1, [2, 3, [4, 5, [6, 7]]], 8, [9, 10]];
const cleanArray = flattenArray(nestedArray);
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy after login
Copy after login

If you would do this in a more traditional way, you would have something like this:

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;
}
Copy after login
Copy after login

All hard work is taken care of by the flat(), and adding Infinity tells it to go down to any level that it may. Simple, clean, and it works.

Object Transform: Deep Clone Without Dependencies

If you need a true deep clone of an object without pulling in lodash? Here's a zero-dependency solution that handles nested objects, arrays, and even dates:

const deepClone = obj => JSON.parse(JSON.stringify(obj));

const complexObj = {
  user: { name: 'Alex', date: new Date() },
  scores: [1, 2, [3, 4]],
  active: true
};

const cloned = deepClone(complexObj);
Copy after login
Copy after login

The old way? You'd have to type something like this:

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;
}
Copy after login
Copy after login

Quick heads-up: This one-liner does have a few limitations - it won't handle functions, symbols, or circular references. But for 90% of use cases, it's pretty much spot on.

String Processing: Convert CSV to Array of Objects

This is a nice little one-liner that takes CSV data and spits out a manipulable array of objects, ideally for use in API responses or reading in data:

const csvToObjects = csv => csv.split('\n').map(row => Object.fromEntries(row.split(',').map((value, i, arr) => [arr[0].split(',')[i], value])));

const csvData = `name,age,city
Peboy,30,New York
Peace,25,San Francisco
Lara,35,Chicago`;

const parsed = csvToObjects(csvData);
// Result:
// [
//   { name: 'Peboy', age: '30', city: 'New York' },
//   { name: 'Peace', age: '25', city: 'San Francisco' },
//   { name: 'Lara', age: '35', city: 'Chicago' }
// ]
Copy after login
Copy after login

Old-fashioned? Oh, you would probably be writing something like this:

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;
}
Copy after login
Copy after login

It's an effective way of doing data transformation with a one-liner, but add some error handling before plunging it into production.

Array Operations: Remove Duplicates and Sort

Here's a shortened one-liner that removes duplicates and sorts your array at the same time, perfect for cleaning a data set:

const uniqueSorted = arr => [...new Set(arr)].sort((a, b) => a - b);

// Example of its use:
const messyArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const cleaned = uniqueSorted(messyArray);
// Result: [1, 2, 3, 4, 5, 6, 9]

// For string sorting

const messyStrings = ['banana', 'apple', 'apple', 'cherry', 'banana'];
const cleanedStrings = [...new Set(messyStrings)].sort();
// Result: ['apple', 'banana', 'cherry']
Copy after login
Copy after login

This is what the old way used to look like:

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);
}
Copy after login
Copy after login

The Set takes care of duplicates perfectly, and then the spread operator turns it back into an array. And you just call sort() afterwards!

DOM Manipulation: Query and Transform Multiple Elements

Here's a powerful one-liner that lets you query and transform multiple DOM elements in one go:

const flattenArray = arr => arr.flat(Infinity);

const nestedArray = [1, [2, 3, [4, 5, [6, 7]]], 8, [9, 10]];
const cleanArray = flattenArray(nestedArray);
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy after login
Copy after login

The traditional approach would be:

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;
}
Copy after login
Copy after login

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

Parallel API Calls with Clean Error Handling

This is another clean line, one-liner that does parallel calls to APIs and does so in very clean error handling.

const deepClone = obj => JSON.parse(JSON.stringify(obj));

const complexObj = {
  user: { name: 'Alex', date: new Date() },
  scores: [1, 2, [3, 4]],
  active: true
};

const cloned = deepClone(complexObj);
Copy after login
Copy after login

More verbose would be:

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;
}
Copy after login
Copy after login

Promise.allSettled is the hero here; it doesn't fail if one request fails and it gives back clean status information for each call.

Date/Time Formatting: Clean Date Strings Without Libraries

Here's a sweet one-liner that turns dates into clean, readable strings without any external dependencies:

const csvToObjects = csv => csv.split('\n').map(row => Object.fromEntries(row.split(',').map((value, i, arr) => [arr[0].split(',')[i], value])));

const csvData = `name,age,city
Peboy,30,New York
Peace,25,San Francisco
Lara,35,Chicago`;

const parsed = csvToObjects(csvData);
// Result:
// [
//   { name: 'Peboy', age: '30', city: 'New York' },
//   { name: 'Peace', age: '25', city: 'San Francisco' },
//   { name: 'Lara', age: '35', city: 'Chicago' }
// ]
Copy after login
Copy after login

The old-school way would look like this:

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;
}
Copy after login
Copy after login

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

Event Handling: Debounce Without the Bloat

Here's a clean one-liner that creates a debounced version of any function - perfect for search input or window resize handlers:

const uniqueSorted = arr => [...new Set(arr)].sort((a, b) => a - b);

// Example of its use:
const messyArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const cleaned = uniqueSorted(messyArray);
// Result: [1, 2, 3, 4, 5, 6, 9]

// For string sorting

const messyStrings = ['banana', 'apple', 'apple', 'cherry', 'banana'];
const cleanedStrings = [...new Set(messyStrings)].sort();
// Result: ['apple', 'banana', 'cherry']
Copy after login
Copy after login

The traditional way would look like this:

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);
}
Copy after login
Copy after login

This one-liner covers all basic debouncing use cases and saves you from calling functions unnecessarily, especially when inputs are generated in rapid succession like typing or resizing.

Local Storage: Object Storage with Validation

Here's just another clean one-liner that handles object storage in localStorage with built-in validation and error handling:

const modifyElements = selector => Array.from(document.querySelectorAll(selector)).forEach(el => el.style);

// Use it like this:
const updateButtons = modifyElements('.btn')
  .map(style => Object.assign(style, {
    backgroundColor: '#007bff',
    color: 'white',
    padding: '10px 20px'
}));

// Or even simpler for class updates:
const toggleAll = selector => document.querySelectorAll(selector).forEach(el => el.classList.toggle('active'));
Copy after login

The old way would need something like this:

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';
  }
}
Copy after login

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

Wrapping Up

These one-liners 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 one-liner makes your code harder to understand, break it down into multiple lines.

Feel free to mix and match these patterns in your projects, and don't forget to check browser compatibility for newer JavaScript features like flat() or Intl.DateTimeFormat if you're supporting older browsers.

Got your own powerful JavaScript one-liners? I'd love to see them!

Follow me on X for more JavaScript tips, tricks, and discussions about web development. I regularly share code snippets and best practices that make our dev lives easier.

Stay curious, keep coding, and remember: good code is not about how little you write, but how clearly you express your intent.

The above is the detailed content of avaScript One-Liners That Replace Lines of Code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles