DEV Community

Cover image for Boost Your JavaScript Efficiency: 20 One-Liner Examples for Quick Coding
Sh Raj
Sh Raj

Posted on

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

Here are some examples of top JavaScript one-liners:

Find the maximum value in an array:

const max = Math.max(...array);
Enter fullscreen mode Exit fullscreen mode

Filter an array to remove duplicates:

const unique = [...new Set(array)]
Enter fullscreen mode Exit fullscreen mode

Convert a string to title case:

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

Check if an array includes a certain value:

const includesValue = array.includes(value);
Enter fullscreen mode Exit fullscreen mode

Reverse a string:

const reversedString = str.split("").reverse().join("");
Enter fullscreen mode Exit fullscreen mode

Get the sum of an array:

const sum = array.reduce((acc, curr) => acc + curr, 0);
Enter fullscreen mode Exit fullscreen mode

Shuffle an array:

const shuffledArray = array.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

Find the average of an array:

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

Check if a value is a number:

const isNumber = value => !isNaN(value);
Enter fullscreen mode Exit fullscreen mode

Get the current date in ISO format:

const currentDate = new Date().toISOString().slice(0, 10);
Enter fullscreen mode Exit fullscreen mode

Check if an array is empty:

const isEmpty = array.length === 0;
Enter fullscreen mode Exit fullscreen mode

Convert a number to a string with commas:

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

Find the smallest value in an array:

const min = Math.min(...array);
Enter fullscreen mode Exit fullscreen mode

Remove a specific value from an array:

const newArray = array.filter(value => value !== toRemove);
Enter fullscreen mode Exit fullscreen mode

Find the index of a specific value in an array:

const index = array.indexOf(value);
Enter fullscreen mode Exit fullscreen mode

Get the last element of an array:

const lastElement = array[array.length - 1];
Enter fullscreen mode Exit fullscreen mode

Sort an array of objects by a specific property:

const sortedArray = array.sort((a, b) => a.property - b.property);
Enter fullscreen mode Exit fullscreen mode

Merge two arrays:

const mergedArray = [...array1, ...array2];
Enter fullscreen mode Exit fullscreen mode

Check if a string contains a specific substring:

const containsSubstring = str.includes(substring);
Enter fullscreen mode Exit fullscreen mode

Reverse the order of words in a string:

const reversedWords = str.split(" ").reverse().join(" ");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)