Mastering JavaScript with One-Liners: Top 20 Examples for Efficient Coding

Boost Your JavaScript Efficiency: 20 One-Liner Examples for Quick Coding

Mar 6, 2023·

2 min read

Play this article

Table of contents

No heading

No headings in the article.

Here are some examples of top JavaScript one-liners:

Find the maximum value in an array:

const max = Math.max(...array);

Filter an array to remove duplicates:

const unique = [...new Set(array)]

Convert a string to title case:

const titleCase = str => str.toLowerCase().replace(/(^|\s)\S/g, t => t.toUpperCase());

Check if an array includes a certain value:

const includesValue = array.includes(value);

Reverse a string:

const reversedString = str.split("").reverse().join("");

Get the sum of an array:

const sum = array.reduce((acc, curr) => acc + curr, 0);

Shuffle an array:

const shuffledArray = array.sort(() => Math.random() - 0.5);

Find the average of an array:

const avg = array.reduce((acc, curr) => acc + curr, 0) / array.length;

Check if a value is a number:

const isNumber = value => !isNaN(value);

Get the current date in ISO format:

const currentDate = new Date().toISOString().slice(0, 10);

Check if an array is empty:

const isEmpty = array.length === 0;

Convert a number to a string with commas:

const numberWithCommas = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

Find the smallest value in an array:

const min = Math.min(...array);

Remove a specific value from an array:

const newArray = array.filter(value => value !== toRemove);

Find the index of a specific value in an array:

const index = array.indexOf(value);

Get the last element of an array:

const lastElement = array[array.length - 1];

Sort an array of objects by a specific property:

const sortedArray = array.sort((a, b) => a.property - b.property);

Merge two arrays:

const mergedArray = [...array1, ...array2];

Check if a string contains a specific substring:

const containsSubstring = str.includes(substring);

Reverse the order of words in a string:

const reversedWords = str.split(" ").reverse().join(" ");

Did you find this article valuable?

Support Binarydiods by becoming a sponsor. Any amount is appreciated!